Search Unity

Calling method from another script, not updating array

Discussion in 'Scripting' started by frasderp, Jun 27, 2020.

  1. frasderp

    frasderp

    Joined:
    Oct 6, 2016
    Posts:
    19
    I am sure this is an easy fix here guys.

    I have two scripts, with an array in one, and a method that checks gameobjects with a tag, to build the array. However, when I call this method from another script, the array does not refresh.

    Script 1

    Code (CSharp):
    1. public class GameScore : MonoBehaviour
    2. {
    3.     public TextMeshProUGUI scoreText;
    4.     public UFOFollow UFOFollowClass;
    5.     public GameObject[] cowsArray;
    6.     private float scoreTime;
    7.     private float startTime;
    8.  
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         cowsArray = GameObject.FindGameObjectsWithTag("Cow");
    14.         startTime = Time.time;
    15.  
    16.     }  
    17.  
    18.     void Update()
    19.     {
    20.         scoreTime = Time.time - startTime;
    21.         scoreText.text = cowsArray.Length.ToString();
    22.  
    23.         // scoreText.text = scoreTime.ToString("f0");
    24.     }
    25.  
    26. public void refreshCowArray()
    27.     {
    28.         cowsArray = GameObject.FindGameObjectsWithTag("Cow");
    29.     }
    Script 2

    Code (CSharp):
    1. public class UFOFollow : MonoBehaviour
    2. {
    3.    
    4.     public GameScore gameScoreManager;
    5.    
    6.     private void Start()
    7.     {
    8.  
    9.     }
    10.  
    11.     void Update()
    12.     {
    13.  
    14.         gameScoreManager.refreshCowArray();
    15.  
    16.     }
    17. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Are you getting any errors in your console? How many copies of GameScore are in the scene?
     
  3. frasderp

    frasderp

    Joined:
    Oct 6, 2016
    Posts:
    19
    Not getting any errors, and only one copy of GameScore in the scene.

    The "reference" is working, as I can read the array length correctly, for example, in the second class. Calling the method to have the array length change is not working however (as gameobjects get destroyed for example). But if I call the method in the original class, it works fine.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    How do you know it's not updating?
     
  5. frasderp

    frasderp

    Joined:
    Oct 6, 2016
    Posts:
    19
    Ok, I've just checked with Debug.log and it is updating, however the UI text is not updating (scoreText.text = cowsArray.Length.ToString();) - this line.

    Why would the array length be different between ToString, and Debug.log ?