Space Invaders With 2 Errors Unity - c#

I have an issue with increasing the score in my space invaders clone. I have 2 errors.
Assets/Scripts/ScoreManager.cs(26,12): error CS0103: The name
`retryLevel' does not exist in the current context
Assets/Scripts/ScoreManager.cs(55,43): error CS1061: Type int' does
not contain a definition forTostring' and no extension method
Tostring' of typeint' could be found. Are you missing an assembly
reference?
Where and what exactly in my script should I change?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
int i = 0;
public GameObject HighScoreDisplay;
public Text scoreDisplay;
public int score = 0;
public Text[] highScoreTables;
private void Start()
{
if (HighScoreDisplay == null || scoreDisplay == null) {
Debug.LogWarning("Values are missing on the ScoreManager!");
return;
}
retryLevel();
}
private void update()
{
scoreDisplay.text = score.ToString();
}
public void ModifyScore(int scoreToAdd)
{
score += scoreToAdd;
}
public void fromScratch(){
score = 0;
HighScoreDisplay.SetActive(false);
}
public void PlayerDied()
{
HighScores.AddScore(score);
foreach (Text table in highScoreTables)
{
table.text = HighScores.scoreTable[i].Tostring();
i++;
}
HighScoreDisplay.SetActive(true);
score = 0;
}
}
public static class HighScores
{
public static List<int> scoreTable = new List<int>{0,0,0};
public static void AddScore(int score)
{
if (score > scoreTable[2])
{
scoreTable[2] = score;
}
else if (score > scoreTable[1])
{
scoreTable[1] = score;
}
else if (score > scoreTable[0])
{
scoreTable[0] = score;
}
}
}

These errors are simple:
your code does not contain definition for function retryLevel nor do I see any static using to be available for importing such a function from other class, (It is a inherited function from MonoBehaviour? Are you sure it has not uppercase first letter according to C# standards?)
you have Tostring with small S. It should be ToString.

Related

text mesh pro text isnt going in text slot

So apparently, i was working on my games dialogue and of course, i have to put the text in the text slot for my code. I tried putting it in the slot but it didnt work. I tried changing the "Text" to "TextMesh" but still, didnt work.
this is my code that i tried for the game.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Goose : MonoBehaviour
{
public GameObject dialoguePanel;
public TextMesh dialogueText;
public string[] dialogue;
private int index;
public float wordSpeed;
public bool playerIsClose;
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.E) && playerIsClose)
{
if(dialoguePanel.activeInHierarchy)
{
zeroText();
}
else
{
dialoguePanel.SetActive(true);
StartCoroutine(Typing());
}
}
}
public void zeroText()
{
dialogueText.text = "";
index = 0;
dialoguePanel.SetActive(false);
}
IEnumerator Typing()
{
foreach(char letter in dialogue[index].ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(wordSpeed);
}
}
public void NextLine()
{
if(index < dialogue.Length - 1)
{
index++;
dialogueText.text = "";
StartCoroutine(Typing());
}
else
{
zeroText();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
playerIsClose = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
playerIsClose = false;
zeroText();
}
}
}
I think what you need is public TMP_Text dialogueText

C# Unity Inventory - List.FindAll() not working as expected

I am super new to C#, so apologies if this is a simple question or has already been answered. I've been looking at other SO questions, trying the exact methods they use, and am still having no luck.
In Unity, I have an Inventory Object class that I can use to create Inventories in my game:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory System/Inventory")]
public class InventoryObject : ScriptableObject
{
public List<InventorySlot> Container = new List<InventorySlot>();
public void AddItem(ItemObject newItem, int itemAmount)
{
bool inventoryHasItem = false;
for (int i = 0; i < Container.Count; i++)
{
if (CurrentSlotHasItem(Container[i], newItem)) {
if (Container.FindAll((InventorySlot currentSlot) => CurrentSlotHasItem(currentSlot, newItem)).Count < newItem.maxStackSize)
{
Container[i].AddAmount(itemAmount);
inventoryHasItem = true;
break;
}
}
}
if (!inventoryHasItem)
{
Container.Add(new InventorySlot(newItem, itemAmount));
}
}
private bool CurrentSlotHasItem(InventorySlot currentSlot, ItemObject item)
{
return currentSlot.item == item;
}
}
[System.Serializable]
public class InventorySlot
{
public ItemObject item;
public int amount;
public InventorySlot(ItemObject _item, int _amount)
{
item = _item;
amount = _amount;
}
public void AddAmount(int value)
{
amount += value;
}
}
This works great, except for this line:
Container.FindAll((InventorySlot currentSlot) => CurrentSlotHasItem(currentSlot, newItem)).Count < newItem.maxStackSize
For some reason, no matter what I use for the findAll() predicate, I always get the same amount in my inspector - 1. Which means that .Count never goes above 1, and I can go way above my ItemObject.maxStackSize.
This is an example ItemObject class I have:
using UnityEngine;
[CreateAssetMenu(fileName = "New Food Object", menuName = "Inventory System/Items/Food")]
public class FoodObject : ItemObject
{
public int healthAmount;
private void Awake() {
type = ItemType.Food;
maxStackSize = 25;
}
}
This is also my Player script that adds the items to the inventory. It just adds them based off of OnTriggerEnter.
public class Player : MonoBehaviour
{
public InventoryObject inventory;
private void OnTriggerEnter(Collider other)
{
var item = other.GetComponent<Item>();
if (item)
{
inventory.AddItem(item.item, 1);
Destroy(other.gameObject);
}
}
}
Here's some screenshots of my Unity console/inspector, with these two lines added to my InventoryObject class. You can see that .Count never going above 1.
if (CurrentSlotHasItem(Container[i], newItem)) {
Debug.Log(Container.FindAll((InventorySlot currentSlot) => CurrentSlotHasItem(currentSlot, newItem)).Count);
Debug.Log(Container[i].amount);
// rest of class
I don't know what I was thinking here. All I needed to do to get maxStackSize to work was changing the logic inside of AddItem:
for (int i = 0; i < Container.Count; i++)
{
if (Container[i].item.id == newItem.id) {
if (Container[i].amount < newItem.maxStackSize)
{
Container[i].AddAmount(itemAmount);
inventoryHasItem = true;
break;
}
}
}
It just compares Container[i].amount to newItem.maxStackSize. If it's under, it will stack the item. Otherwise, it creates a new item in the inventory.

The type or namespace name 'SyncListString' could not be found (are you missing a using directive or an assembly reference? in mirror

Hey i am beginer and i am making a multiplayer game using mirror by watching https://www.youtube.com/watch?v=w0Dzb4axdcw&list=PLDI3FQoanpm1X-HQI-SVkPqJEgcRwtu7M&index=3 this video in this video he has maded match maker script and i have maded it step by step but don't know why i am getting this error i have seen code many times and all the things are same but he is not getting any error but i am plzz help this is my code and plzz explain in simply i am beginner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
namespace MirrorBasics {
[System.Serializable]
public class Match {
public string matchID;
public SyncListGameObject players = new SyncListGameObject ();
public Match(string matchID, GameObject player) {
this.matchID = matchID;
players.Add (player);
}
public Match () { }
}
[System.Serializable]
public class SyncListGameObject : SyncList<GameObject> { }
[System.Serializable]
public class SyncListMatch : SyncList<Match> { }
public class MatchMaker : NetworkBehaviour {
public static MatchMaker instance;
public SyncListMatch matches = new SyncListMatch ();
public SyncListString matchIDs = new SyncListString ();
void Start() {
instance = this;
}
public bool HostGame (string _matchID, GameObject _player) {
if (!matchIDs.Contains(_matchID)) {
matchIDs.Add (_matchID) ;
matches.Add (new Match (_matchID, _player));
Debug.Log ($"Match generated");
return true;
} else {
Debug.Log ($"Match ID already exists");
return false;
}
}
public static string GetRandomMatchID () {
string _id = string.Empty;
for (int i = 0; i < 5; i++) {
int random = Random.Range(0, 36);
if (random < 26) {
_id += (char)(random + 65);
} else {
_id += (random - 26).ToString ();
}
}
Debug.Log($"Random Match ID: {_id}");
return _id;
}
}
}
Like SyncListGameObject create SyncList with string like this.
public class SyncListString: SyncList<string>()
Then
public SyncListString matchIDs = new SyncListString();
I made lobby/matchmaking by this tutorial too :)

Assets\Scripts\InGamePanel.cs(6,1): error CS1022: Type or namespace definition, or end-of-file expected

hi i get this errors using unity
1 ==> Assets\Scripts\InGamePanel.cs(6,1): error CS1022: Type or namespace definition, or end-of-file expected
2 ==> Assets\Scripts\InGamePanel.cs(110,1): error CS1022: Type or namespace definition, or end-of-file expected
the script :
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
{
private void Start()
{
bool interstitialsDisabled = LvlBtnHandler.activeStage > 0 && LvlBtnHandler.activeLevel > 0 && StageModel.IsFirstStage(LvlBtnHandler.activeStage) && !GameState.Instance.HasLevelAccess(StageModel.GetSecondStageId(), 1) && !StageModel.IsLastLevel();
//LionAdManager.Instance.SetInterstitialsDisabled(interstitialsDisabled);
Button[] componentsInChildren = base.GetComponentsInChildren<Button>();
componentsInChildren[2].onClick.AddListener(new UnityAction(this.ShowHomeModal));
}
private void Update()
{
}
private void Exit()
{
UnityEngine.Object.Destroy(this.modal);
}
public void ShowHomeModal()
{
GameObject gameObject = GameObject.Find("NewCanvas02");
this.modal = UnityEngine.Object.Instantiate<GameObject>(Resources.Load<GameObject>("Prefabs/HomeModal"), gameObject.transform);
Button[] componentsInChildren = this.modal.GetComponentsInChildren<Button>();
componentsInChildren[0].onClick.AddListener(new UnityAction(this.Exit));
componentsInChildren[1].onClick.AddListener(new UnityAction(this.Menu));
componentsInChildren[2].onClick.AddListener(new UnityAction(this.Exit));
}
public void Menu()
{
//if (SceneManager.GetActiveScene().name != "Customization" && !AFtitle.noAds && LionAdManager.Instance.IsTimeToShowIntersitial() && LvlBtnHandler.activeStage != 0)
{
AFtitle.watchedReward = false;
//LionAdManager.Instance.MaybeShowInterstitial();
}
//if (AppLovinCrossPromo.Instance() != null)
//{
// AppLovinCrossPromo.Instance().HideMRec();
//}
if (LvlBtnHandler.activeStage == 0)
{
Time.timeScale = 1f;
}
PlayerBF.jumped = false;
PlayerBF.land = false;
PlayerBF.fallen = false;
SceneManager.LoadScene("NewLvlSelect");
}
public void NextStage()
{
LvlBtnHandler.activeStage++;
LvlBtnHandler.activeLevel = 1;
string[] array = new string[]
{
string.Empty,
"GymNew",
"MountNew",
"City",
"House",
"Gallery",
"Ship"
};
SceneManager.LoadScene(array[LvlBtnHandler.activeStage]);
}
private void GameOver()
{
this.gameOverPanel.SetActive(true);
base.Invoke("Restart", 2f);
}
public void LevelCompleted()
{
this.lvlCompletePanel.SetActive(true);
GameObject.Find("Score").GetComponent<Score>().SetTotalScore();
GameObject.Find("Score").GetComponent<Score>().FinishedLevel();
}
public GameObject gameOverPanel();
public GameObject lvlCompletePanel();
private GameObject modal();
}
please any help for this issue i get this problem for many times
You cannot code methods in the global namespace directly. These need to go inside a class.
If you want Start() and Update() you need it to derive from monobehaviour. Put your code inside this trial class and name it as you wish. Remember the name of the script should be the same of the class with .cs, for this class for example should be TrialClass.cs, so that you can attach scripts to gameobjects.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrialClass : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}

calling an array of gameobjects' script called 'apple' from a script called 'money'

(In unity 2D)So I have a script for the amount of money and apples I have in my game and want to make more than 1 game object have the amount of apples script. btw there IS a void TransferMoney and IS public. I do this, and I need to transfer the amount of money i have to the apple script but because it's an array it does the following error: (55,16): error CS1061: 'apple[]' does not contain a definition for 'TransferMoney' and no accessible extension method 'TransferMoney' accepting a first argument of type 'apple[]' could be found (are you missing a using directive or an assembly reference?) Here's the money script:
public class numberofmoney : MonoBehaviour //script in the Text UI "amount of money" {
static public int scenemoney;
public string house;
public string shopString;
public TMP_Text moneyText;
public cookie1 Cookie;
public apple[] apples;
public void BoughtApple(int currentAOM)//aom stands for 'amount of money'
{
scenemoney = currentAOM;
}
void Awake()
{
apples = GameObject.FindObjectsOfType<apple>(); //finds apple
}
void Start()
{
Scene cookie = SceneManager.GetActiveScene();
house = cookie.name; //checks scene and does part of converting to string
Scene shop = SceneManager.GetActiveScene();
shopString = shop.name; //checks scene and does part of converting to string
}
public void forCookie(int money)
{
scenemoney = money;
}
void Update()
{
string scenemoneystring = scenemoney.ToString();
moneyText.SetText(scenemoneystring); //Converts money and sets text
if (house == "House") { //transfers money between scripts #1
Cookie.transferMoney(scenemoney);
}
if (shopString == "store") { //transfers money between scripts #2
apples.TransferMoney(scenemoney);
}
}
}
and apples script:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro;
public class apple : MonoBehaviour {
public string appleString;
public int publicMoney;
public int Apples;
public NumberOfApples numberOfApples;
public TMP_Text tmp;
public numberofmoney NumberOfMoney;
void Awake()
{
numberOfApples = GameObject.FindObjectOfType<NumberOfApples>();
NumberOfMoney = GameObject.FindObjectOfType<numberofmoney>();
}
public void TransferMoney(int money)
{
publicMoney = money;
}
void OnTriggerEnter2D(Collider2D trigger)
{
if (publicMoney >= 10){
Destroy(this.gameObject);
Apples++;
publicMoney -= 10;
appleString = Apples.ToString();
tmp.SetText(appleString);
NumberOfMoney.BoughtApple(publicMoney);
}
numberOfApples.transferApples(Apples);
}
}
For what I can see, you're doing:
apples.TransferMoney(scenemoney);
but apples is an array of the class apple, you can't call the "transferMoney" method, you need to iterate each object of the array and call the transferMoney method individually.
foreach(apple a in apples){
a.TransferMoney(scenemoney);
}
hope that helps!
Edited: copy paste error called by derHugo

Categories

Resources