Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. We're looking for your feedback on the platforms you use and how you use them. Let us know!
    Dismiss Notice
  4. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  6. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  7. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  8. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Gold not getting added

Discussion in 'Scripting' started by Vexer, Aug 12, 2018 at 10:23 AM.

  1. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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):
    1.  
    2. //Buttons:
    3.     public Button Slot1;
    4.  
    5.     void Start()
    6.     {
    7.         Slot1.onClick.AddListener(CollectGold);
    8.     }
    9.  
    This is the CollectGold void:
    Code (csharp):
    1.  
    2. public void CollectGold()
    3.     {
    4.         goldmanager.Gold += 10;
    5.         Debug.Log("Collected Gold!!");
    6.         Destroy(GameObject.FindWithTag("LootSlot1"));
    7.     }
    8.  
    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):
    1.  
    2.       goldmanager.Gold += 10;
    3.  
    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):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class GoldManager : MonoBehaviour {
    8.  
    9.     //Ints:
    10.     public int Gold = 0;
    11.     [HideInInspector]
    12.     public int lvl1;
    13.  
    14.     //Texts:
    15.     public Text GoldDisplay;
    16.  
    17.     // Use this for initialization
    18.     void Start () {
    19.     }
    20.    
    21.     // Update is called once per frame
    22.     void Update () {
    23.         GoldDisplay.text = Gold.ToString();
    24.     }
    25.  
    26.     public void RandomGoldAmount()
    27.     {
    28.         lvl1 = Random.Range(5, 25);
    29.     }
    30. }
    31.  
    so this is my issue please help!!
     
    Last edited: Aug 12, 2018 at 10:32 AM
  2. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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??
     
    Last edited: Aug 12, 2018 at 10:31 AM
  3. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    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.
     
  4. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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..
     
  5. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    The Gold value in GoldManager is public. Are there any other code lines that play around with that value?
     
  6. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    No
     
  7. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    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?
     
  8. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class LootManager : MonoBehaviour {
    8.  
    9.     //Scripts:
    10.     public GoldManager goldmanager;
    11.  
    12.     //Bools:
    13.     public bool GoldCollected;
    14.     public bool LootCollected;
    15.     public bool OpeningLoot;
    16.  
    17.     //Canvas:
    18.     public Canvas Loot;
    19.  
    20.     //Buttons:
    21.     public Button Slot1;
    22.     public Button Slot2;
    23.  
    24.     void Start()
    25.     {
    26.         Slot1.onClick.AddListener(CollectGold);
    27.         Slot2.onClick.AddListener(CollectLoot);
    28.     }
    29.     void Update()
    30.     {
    31.         if (OpeningLoot == true)
    32.         {
    33.             Cursor.lockState = CursorLockMode.None;
    34.             Cursor.visible = true;
    35.         }
    36.  
    37.         if (OpeningLoot == false)
    38.         {
    39.             Cursor.lockState = CursorLockMode.Locked;
    40.             Cursor.visible = false;
    41.         }
    42.     }
    43.  
    44.     public void OpenLoot()
    45.     {
    46.         OpeningLoot = true;
    47.         Canvas loot = Instantiate(Loot) as Canvas;
    48.     }
    49.  
    50.     public void CollectGold()
    51.     {
    52.         goldmanager.RandomGoldAmount();
    53.         goldmanager.Gold += goldmanager.lvl1;
    54.         Debug.Log("Collected Gold!!");
    55.         Destroy(GameObject.FindWithTag("LootSlot1"));
    56.     }
    57.  
    58.     public void CollectLoot()
    59.     {
    60.         Debug.Log("Collected Loot!!");
    61.         Destroy(GameObject.FindWithTag("LootSlot2"));
    62.     }
    63.  
    64.     public void CloseLoot()
    65.     {
    66.         OpeningLoot = false;
    67.         Destroy(GameObject.FindWithTag("LootUI"));
    68.     }
    69. }
    70.  
    Code (csharp):
    1.  
    2.  
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6. using UnityEngine.UI;
    7.  
    8. public class GoldManager : MonoBehaviour {
    9.  
    10.     //Ints:
    11.     public int Gold = 0;
    12.     [HideInInspector]
    13.     public int lvl1;
    14.  
    15.     //Texts:
    16.     public Text GoldDisplay;
    17.  
    18.     // Use this for initialization
    19.     void Start () {
    20.     }
    21.    
    22.     // Update is called once per frame
    23.     public void Update () {
    24.         GoldDisplay.text = Gold.ToString();
    25.     }
    26.  
    27.     public void RandomGoldAmount()
    28.     {
    29.         lvl1 = Random.Range(5, 25);
    30.     }
    31. }
    32.  
    Code (csharp):
    1.  
    2.  
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6.  
    7.  
    8. public class PlayerController : MonoBehaviour
    9. {
    10.     //Scripts:
    11.     public LootManager lootmanager;
    12.     public DropManager dropmanager;
    13.     public GoldManager goldmanager;
    14.     public EnemyHealth enemyHealth;
    15.  
    16.     //Camera:
    17.     public Camera cam;
    18.  
    19.     //Floats:
    20.     public float speed = 5.0F;
    21.     float distance = 5f;
    22.  
    23.     //Rigidbody:
    24.     public Rigidbody rb;
    25.  
    26.     //Ints:
    27.     private int range = 3;
    28.     private int collectrange = 3;
    29.  
    30.     //Vector3:
    31.     public Vector3 moveDirection;
    32.  
    33.     void Start()
    34.     {
    35.     }
    36.  
    37.     void FixedUpdate()
    38.     {
    39.         Vector3 viewDir = Camera.main.transform.forward;
    40.  
    41.         viewDir.y = 0;
    42.         viewDir.Normalize();
    43.  
    44.         Quaternion viewRot = Quaternion.LookRotation(viewDir);
    45.  
    46.         // player transform
    47.         transform.rotation = Quaternion.Slerp(transform.rotation, viewRot, 10f * Time.deltaTime);
    48.  
    49.         float vertical = (Input.GetAxisRaw("Vertical") * speed);
    50.         float horizontal = (Input.GetAxisRaw("Horizontal") * speed);
    51.  
    52.         vertical *= Time.deltaTime;
    53.         horizontal *= Time.deltaTime;
    54.         transform.Translate(horizontal, 0, vertical);
    55.  
    56.     }
    57.  
    58.     EnemyHealth prevEnemyHealth;
    59.  
    60.     void Update()
    61.     {
    62.         if (Input.GetMouseButtonDown(0))
    63.         {
    64.             Attack();
    65.         }
    66.  
    67.         if (Input.GetKeyDown("e"))
    68.         {
    69.             Collect();
    70.         }
    71.  
    72.         if (Input.GetKeyDown("escape"))
    73.         {
    74.             if (lootmanager.OpeningLoot)
    75.             {
    76.                 lootmanager.CloseLoot();
    77.             }
    78.         }
    79.     }
    80.     void Attack()
    81.     {
    82.         RaycastHit hit;
    83.         if (Physics.Raycast(transform.position, transform.forward, out hit, range))
    84.         {
    85.             if (hit.transform.tag == "Enemy")
    86.             {
    87.                 if (prevEnemyHealth != null)
    88.                 {
    89.                     prevEnemyHealth._healthSlider.SetActive(false);
    90.                 }
    91.                 prevEnemyHealth = hit.transform.GetComponent<EnemyHealth>();
    92.                 hit.transform.GetComponent<EnemyHealth>()._healthSlider.SetActive(true);
    93.                 hit.transform.GetComponent<EnemyHealth>().Health -= 10;
    94.                 Debug.DrawRay(transform.position, transform.forward * range, Color.yellow);
    95.             }
    96.         }
    97.     }
    98.  
    99.     void Collect()
    100.     {
    101.         Vector3 rayDirection = transform.TransformDirection(Vector3.forward);
    102.         RaycastHit hit;
    103.         if (Physics.Raycast(transform.position - transform.up * 0.75f, rayDirection, out hit, collectrange))
    104.         {
    105.  
    106.             if (hit.transform.tag == "Drop")
    107.             {
    108.                 lootmanager.OpenLoot();
    109.                 Destroy(hit.transform.gameObject);
    110.                 Debug.Log("Opening loot!!");
    111.             }
    112.  
    113.         else
    114.         {
    115.             Debug.DrawRay(transform.position - transform.up * 0.75f, rayDirection * collectrange);
    116.         }
    117.         }
    118.     }
    119. }
    120.  
     
  9. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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).....
     
  10. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    I want to know what both scripts think the value of Gold is directly (i.e. not using the UI element).
     
  11. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    Results:
     

    Attached Files:

  12. Cucci_A

    Cucci_A

    Joined:
    Jan 23, 2018
    Posts:
    229
    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.
     
  13. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    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.
     
  14. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    They are both just references to the same script...
     
    Last edited: Aug 12, 2018 at 5:56 PM
  15. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    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?
     
  16. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    it dissapears
     
  17. VergilUa

    VergilUa

    Joined:
    Dec 22, 2014
    Posts:
    515
    Convert the "Gold" property to an actual property. With get; set; that contains Debug.Log.
    Code (CSharp):
    1. public int Gold {
    2.    get{
    3.       Debug.Log("Checking value");
    4.       return _gold;
    5.    }
    6.    set{
    7.      Debug.Log("Setting value - "+value);
    8.      _gold = value;
    9.    }
    10. }
    11. 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.
     
    Last edited: Aug 12, 2018 at 6:19 PM
  18. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    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):
    1.     #region Public interface
    2.     public void SetRandomGoldAmount()
    3.     {
    4.         m_rndAdd = Random.Range(5, 25);
    5.     }
    6.  
    7.     public void AddGold()
    8.     {
    9.         m_gold += m_rndAdd;
    10.         GoldDisplay.text = m_gold.ToString();
    11.         Debug.Log("Gold is: " + m_gold);
    12.     }
    13.     #endregion
    14.  
    15.  
    16.     void Start()
    17.     {
    18.         SetRandomGoldAmount();
    19.     }
    20.  
    21. #pragma warning disable 649
    22.     [SerializeField] Text GoldDisplay;
    23. #pragma warning restore 649
    24.  
    25.     int m_gold;
    26.     int m_rndAdd;
     
  19. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class GoldManager : MonoBehaviour {
    8.  
    9.     #region Public interface
    10.     public void SetRandomGoldAmount()
    11.     {
    12.         m_rndAdd = Random.Range(5, 25);
    13.     }
    14.  
    15.     public void AddGold()
    16.     {
    17.         m_gold += m_rndAdd;
    18.         Debug.Log("Gold is: " + m_gold);
    19.     }
    20.     #endregion
    21.  
    22.  
    23.     void Start()
    24.     {
    25.         SetRandomGoldAmount();
    26.     }
    27.  
    28. #pragma warning disable 649
    29. #pragma warning restore 649
    30.  
    31.     int m_gold;
    32.     int m_rndAdd;
    33. }
    34.  
     
  20. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    The value shown is non-zero. Why do you think it is still wrong?
     
  21. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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..
     
  22. Cucci_A

    Cucci_A

    Joined:
    Jan 23, 2018
    Posts:
    229
    Oops, my bad. I thought they meant the GoldManager was only being used in one object.
     
  23. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    I just still don't understand what was wrong with my code to me it seemed fine but it still didn't work..
     
  24. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    Ok, so now you need to start debugging. . . . .
     
  25. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    I have just tried your GoldManager (from Post #19) in a new scene and it worked correctly.
     
  26. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    With using all the other scripts too??
     
  27. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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??
     
  28. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,083
    No. That is what we are currently trying to get to the bottom of. :)
     
  29. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    185
    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...