Hey guys! i have a stupid problem with my code and i don't know how to fix it... so i have made some scripts to collect gold and then it should be added to your gold value if you press on the gold button but for some reason the gold button does work BUT your gold value stays at 0 please help! So this is the code for if you press on the button: Code (csharp): //Buttons: public Button Slot1; void Start() { Slot1.onClick.AddListener(CollectGold); } This is the CollectGold void: Code (csharp): public void CollectGold() { goldmanager.Gold += 10; Debug.Log("Collected Gold!!"); Destroy(GameObject.FindWithTag("LootSlot1")); } This void does get called and works because the debug.log works!! But the money doesn't get added and the strange part is that if i take this line: Code (csharp): goldmanager.Gold += 10; and put it in the update instead of the void it DOES add gold every frame to your gold value My goldmanager script: Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GoldManager : MonoBehaviour { //Ints: public int Gold = 0; [HideInInspector] public int lvl1; //Texts: public Text GoldDisplay; // Use this for initialization void Start () { } // Update is called once per frame void Update () { GoldDisplay.text = Gold.ToString(); } public void RandomGoldAmount() { lvl1 = Random.Range(5, 25); } } so this is my issue please help!!
BTW i don't get any errors... And i also found out that if i stop the game after i collected gold it does add gold to the gold value so it looks like gold is not getting updated could this be the issue and how could i fix this??
Is there only a single GoldManager script in your scene? If there is more than one, then you could be adding gold to the wrong one.
Yes there is only 1 goldmanager and like i said in my reply the value does get added but it gets added after i stop playing the game..
The Gold value in GoldManager is public. Are there any other code lines that play around with that value?
Have you tried adding Debug.Log(<..GoldManager..>.Gold); in both CollectGold() and GoladManager.Update()? Do they consistently disagree on the value of Gold until the player's death?
I'll try that and let you know what happends btw these are all my scripts that should make this work so you can check if you see an error while i try what you just said: Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LootManager : MonoBehaviour { //Scripts: public GoldManager goldmanager; //Bools: public bool GoldCollected; public bool LootCollected; public bool OpeningLoot; //Canvas: public Canvas Loot; //Buttons: public Button Slot1; public Button Slot2; void Start() { Slot1.onClick.AddListener(CollectGold); Slot2.onClick.AddListener(CollectLoot); } void Update() { if (OpeningLoot == true) { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } if (OpeningLoot == false) { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } public void OpenLoot() { OpeningLoot = true; Canvas loot = Instantiate(Loot) as Canvas; } public void CollectGold() { goldmanager.RandomGoldAmount(); goldmanager.Gold += goldmanager.lvl1; Debug.Log("Collected Gold!!"); Destroy(GameObject.FindWithTag("LootSlot1")); } public void CollectLoot() { Debug.Log("Collected Loot!!"); Destroy(GameObject.FindWithTag("LootSlot2")); } public void CloseLoot() { OpeningLoot = false; Destroy(GameObject.FindWithTag("LootUI")); } } Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GoldManager : MonoBehaviour { //Ints: public int Gold = 0; [HideInInspector] public int lvl1; //Texts: public Text GoldDisplay; // Use this for initialization void Start () { } // Update is called once per frame public void Update () { GoldDisplay.text = Gold.ToString(); } public void RandomGoldAmount() { lvl1 = Random.Range(5, 25); } } Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { //Scripts: public LootManager lootmanager; public DropManager dropmanager; public GoldManager goldmanager; public EnemyHealth enemyHealth; //Camera: public Camera cam; //Floats: public float speed = 5.0F; float distance = 5f; //Rigidbody: public Rigidbody rb; //Ints: private int range = 3; private int collectrange = 3; //Vector3: public Vector3 moveDirection; void Start() { } void FixedUpdate() { Vector3 viewDir = Camera.main.transform.forward; viewDir.y = 0; viewDir.Normalize(); Quaternion viewRot = Quaternion.LookRotation(viewDir); // player transform transform.rotation = Quaternion.Slerp(transform.rotation, viewRot, 10f * Time.deltaTime); float vertical = (Input.GetAxisRaw("Vertical") * speed); float horizontal = (Input.GetAxisRaw("Horizontal") * speed); vertical *= Time.deltaTime; horizontal *= Time.deltaTime; transform.Translate(horizontal, 0, vertical); } EnemyHealth prevEnemyHealth; void Update() { if (Input.GetMouseButtonDown(0)) { Attack(); } if (Input.GetKeyDown("e")) { Collect(); } if (Input.GetKeyDown("escape")) { if (lootmanager.OpeningLoot) { lootmanager.CloseLoot(); } } } void Attack() { RaycastHit hit; if (Physics.Raycast(transform.position, transform.forward, out hit, range)) { if (hit.transform.tag == "Enemy") { if (prevEnemyHealth != null) { prevEnemyHealth._healthSlider.SetActive(false); } prevEnemyHealth = hit.transform.GetComponent<EnemyHealth>(); hit.transform.GetComponent<EnemyHealth>()._healthSlider.SetActive(true); hit.transform.GetComponent<EnemyHealth>().Health -= 10; Debug.DrawRay(transform.position, transform.forward * range, Color.yellow); } } } void Collect() { Vector3 rayDirection = transform.TransformDirection(Vector3.forward); RaycastHit hit; if (Physics.Raycast(transform.position - transform.up * 0.75f, rayDirection, out hit, collectrange)) { if (hit.transform.tag == "Drop") { lootmanager.OpenLoot(); Destroy(hit.transform.gameObject); Debug.Log("Opening loot!!"); } else { Debug.DrawRay(transform.position - transform.up * 0.75f, rayDirection * collectrange); } } } }
uhm.. now that im reading your reply im not quite sure if i understand what you just said, if you are just wondering if the button is even working then well i have a debug.log in collectgold that does work when i press the button (Like i said before gold only changes after i stop the game.. it almost looks like gold is not getting updated).....
I want to know what both scripts think the value of Gold is directly (i.e. not using the UI element).
There is not, according to the scripts you posted above. You have two separate Goldmanager instances - one in your LootManager class and one in your PlayerController class. Your PlayerController class already has a LootManager reference as well, and since LootManager has a reference to GoldManager, there's no need to have GoldManager referenced in PlayerController; you can just use the LootManager reference instead to interact with the GoldManager.
They are both references though- I do not see them creating any new instances from that object. So they could be referencing one and the same GoldManager. Of course, it is difficult to be sure of that not being able to see the whole project setup.
There 2 main options that I can think of then : (1) they are references to 2 different GoldManagers, or, (2) Something else is instantly setting the value back to zero after the non-zero value is logged out. How about trying this: in the debug log that is showing the non-zero value, have it destroy the GoldManager. Does the (one and only?) GoldManager disappear from the hierarchy or does the game continue on regardless?
Convert the "Gold" property to an actual property. With get; set; that contains Debug.Log. Code (CSharp): public int Gold { get{ Debug.Log("Checking value"); return _gold; } set{ Debug.Log("Setting value - "+value); _gold = value; } } private int _gold; This way you'll be able to track down what's actually adding the values, or changes them, or not changes them at all. This will also allow you to determine to which object the addition goes. Another idea is to move the "GoldManager" script away from the player object. Then, use the search in the hierarchy for "GoldManager" and see if there's duplicates.
VergilUa beat me to it. Let's try tightening up your GoldManager a little. Can you change it's implementation (even if only temporarily) to this. What do you see for the value of gold then? : Code (CSharp): #region Public interface public void SetRandomGoldAmount() { m_rndAdd = Random.Range(5, 25); } public void AddGold() { m_gold += m_rndAdd; GoldDisplay.text = m_gold.ToString(); Debug.Log("Gold is: " + m_gold); } #endregion void Start() { SetRandomGoldAmount(); } #pragma warning disable 649 [SerializeField] Text GoldDisplay; #pragma warning restore 649 int m_gold; int m_rndAdd;
https://gyazo.com/6d61c77bb62a44fd4b88d827d2ca7af1 The text ui kept giving an error that the object reference wasn't set while it was... so i just removed it but this is the result of it still doesn't seem to be right tho... here is my code now: Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GoldManager : MonoBehaviour { #region Public interface public void SetRandomGoldAmount() { m_rndAdd = Random.Range(5, 25); } public void AddGold() { m_gold += m_rndAdd; Debug.Log("Gold is: " + m_gold); } #endregion void Start() { SetRandomGoldAmount(); } #pragma warning disable 649 #pragma warning restore 649 int m_gold; int m_rndAdd; }
Because m_gold = 0 at the start and after collectinggold it should be a value between 5 and 25 but it's alot higher i don't understand where unity is getting that number from..
I just still don't understand what was wrong with my code to me it seemed fine but it still didn't work..
I went back to my old code because i felt like all these new scripts were too complicated and gave problems too the problem with this keeps being that my gold value updates after i stop the game if the game is running and the gold value changes nothing updates untill the game is shutdown and then it will actually update the gold value do you have any idea why??
I found out that it's not my code but it has something to do with the button because if i call the collectgold void when pressing "f" for example it did actually work and the reason my value is not updating only after relaunching the game is because im updating the prefabs gold value and not my gameobjects gold value the only issue i have right now is that i can't drag my gameobject into the onclick area in the inspector and i can only drag and drop the prefab...