Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

List of game objects cleared when accessed from another script

Discussion in '2D' started by zikablu, Jul 29, 2022.

  1. zikablu

    zikablu

    Joined:
    May 26, 2022
    Posts:
    6
    Hello,

    I am new to Unity and have been stuck on this problem for a few days. Any help would be greatly appreciated.

    I am making a simple cafe simulator. Right now I have four table objects that I instantiate at runtime in a TableManager script, attached to a TableGenerator object. I add the tables to a list that I want to manipulate from another script, depending if that table is "occupied" by a customer.

    My problem is that the list clears automatically when referenced to from another script. Currently, I reference the list on a script attached to the Customer GameObject, which is instantiated with a timer. Every time a new customer is instantiated, the list clears from 4 tables to 0. I also tried putting the script on a separate TableBehavior script, since I thought maybe the customer instantiation was the problem, but the list still clears when referenced from this script. Here are the two relevant scripts:

    TableManager:
    Code (CSharp):
    1.  
    2. public class TableManager : MonoBehaviour
    3. {
    4.  
    5.     public GameObject Table;
    6.     public List<GameObject> table_list = new List<GameObject>();
    7.     public List<GameObject> occupied_list = new List<GameObject>();
    8.  
    9.  
    10.     void Awake(){
    11.  
    12.  
    13.         // creating new GO in code and then typecasting them when using instantiate so that we can manipulate them in scripts
    14.         GameObject t1 = (GameObject)Instantiate(Table,
    15.             new Vector3 (-2, 2, 0),
    16.             new Quaternion( 0, 0, 0, 0));
    17.  
    18.         GameObject t2 = (GameObject)Instantiate(Table,
    19.             new Vector3 (-2, -2, 0),
    20.             new Quaternion( 0, 0, 0, 0));
    21.  
    22.         GameObject t3 = (GameObject)Instantiate(Table,
    23.             new Vector3 (2, 2, 0),
    24.             new Quaternion( 0, 0, 0, 0));
    25.  
    26.         GameObject t4 = (GameObject)Instantiate(Table,
    27.             new Vector3 (2, -2, 0),
    28.             new Quaternion( 0, 0, 0, 0));
    29.      
    30.         table_list.Add(t1);
    31.         table_list.Add(t2);
    32.         table_list.Add(t3);
    33.         table_list.Add(t4);
    34.  
    35.     }
    36.  
    CustomerBehavior:

    Code (CSharp):
    1. public class CustomerBehavior : MonoBehaviour
    2. {
    3.     [SerializeField] float customer_speed;
    4.  
    5.     TableManager tm_script;
    6.     [SerializeField] GameObject TableGenerator;
    7.  
    8.     void Awake(){
    9.         // grabbing the tm_script through the GO
    10.         tm_script = TableGenerator.GetComponent<TableManager>();
    11.  
    12.     }
    13.     void Start()
    14.     {
    15.         // this prints 4 until a Customer GO is instantiated, then prints 0
    16.         Debug.Log("_table_list count: " + tm_script.table_list.Count);
    17.  
    18.     }
    19.  
    20.     // returns a random table for the Customer GO to move to
    21.     public GameObject RandomTable() {
    22.  
    23.         // returns int with (min inclusive, max exclusive)
    24.         Debug.Log("in randomTable method, count: " + tm_script.table_list.Count);
    25.         int index = Random.Range(0, tm_script.table_list.Count);
    26.         Debug.Log("index: " + index);
    27.         return tm_script.table_list[index];
    28.  
    29.     }
    30. }
    31.  
    edit: Customer Instantiation script in CustomerManager class


    Code (CSharp):
    1. public class CustomerManager : MonoBehaviour
    2. {
    3.     [SerializeField] float cooldownTimer;
    4.     [SerializeField] float spawnTime;
    5.  
    6.     public GameObject Customer;
    7.  
    8.     // Update is called once per frame
    9.     void Update()
    10.     {
    11.         if(cooldownTimer > spawnTime){
    12.             Instantiate(Customer,
    13.                 new Vector3(transform.position.x, transform.position.y, 0),
    14.                 new Quaternion(0, 0, 0, 0));
    15.             cooldownTimer = 0;
    16.         }
    17.  
    18.         cooldownTimer += Time.deltaTime;
    19.     }
    20. }
     
    Last edited: Jul 30, 2022
  2. Dedi6

    Dedi6

    Joined:
    Jan 20, 2019
    Posts:
    119
    Can you add the part where you instantiate the customer? It's the crux but you left it out.

    Honestly, I'm not the best when it comes to static instances because I use them way too much, but I think a "manager' script is fitting for one. I use them for all of my managers - game managers, audio managers, prefab managers etc. I think it can solve your problem easily, tho it is not a must.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    When you make this public, Unity will wipe it out with whatever is serialized for that property, which I suppose might be null. Instead , make it private, OR, explicitly initialize it before filling it in.

    Here's why:

    Serialized properties in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:

    - what the class constructor makes (either default(T) or else field initializers)

    - what is saved with the prefab

    - what is saved with the prefab override(s)/variant(s)

    - what is saved in the scene and not applied to the prefab

    - what is changed in Awake(), Start(), or even later etc.

    Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.

    Field initializers versus using Reset() function and Unity serialization:

    https://forum.unity.com/threads/sensitivity-in-my-mouselook-script.1061612/#post-6858908

    https://forum.unity.com/threads/crouch-speed-is-faster-than-movement-speed.1132054/#post-7274596

    ALSO: beware of script callback timing:

    Here is some timing diagram help:

    https://docs.unity3d.com/Manual/ExecutionOrder.html

    Two good discussions on Update() vs FixedUpdate() timing:

    https://jacksondunstan.com/articles/4824

    https://johnaustin.io/articles/2019/fix-your-unity-timestep
     
  4. zikablu

    zikablu

    Joined:
    May 26, 2022
    Posts:
    6
    Thank you for your reply! If I understand correctly, any public variable initialized through code in Unity could be overwritten if set somewhere else in Unity or in the code. It is a little confusing to me because the List variable doesn't show up in the inspector, even though it is set to public.

    Could you explain how to explicitly initialize the list before filling it in? I'm not sure how to do that, and I would like to access the list from other scripts so I don't think I can change it to private.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    Oh you just
    new
    it up (but don't declare a local variable), but in code right before you add to it.
     
  6. zikablu

    zikablu

    Joined:
    May 26, 2022
    Posts:
    6
    Hi thank you for your reply, I just edited the post to add the customer instantiation script. It is attached to an empty GO CustomerGenerator, while the CustomerBehavior script is attached to the Customer object that gets instantiated with the timer. The list of tables seems to clear every time a Customer object is instantiated.
     
  7. zikablu

    zikablu

    Joined:
    May 26, 2022
    Posts:
    6
    Hello,

    I tried declaring the List at the top of the file like this:
    Code (CSharp):
    1. public List<GameObject> table_list;
    and then in the Awake method initializing the List with the new keyword like this:

    Code (CSharp):
    1. table_list = new List<GameObject>{t1, t2, t3, t4};
    but the problem still persists, so I am not sure I am doing it correctly.
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    Does that call the initialization code?

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    You must find a way to get the information you need in order to reason about what the problem is.
     
  9. rarac

    rarac

    Joined:
    Feb 14, 2021
    Posts:
    570
    why do you say you cant see the list of tables on the inspector?

    post a screenshot of the game object of the inspector where you have your table generator
     
  10. zikablu

    zikablu

    Joined:
    May 26, 2022
    Posts:
    6
    Update: Solved! The problem was the way I was referencing the script. I was trying to reference the TableManager script containing the list through a GO on a script that was attached to the Customer GO, which was being instantiated with a timer and I believe therefore not saving the GO reference. In the Awake() method of the CustomerBehavior script, I deleted the GO declaration I was trying to reference the script through, and changed

    Code (CSharp):
    1. tm_script = TableGenerator.GetComponent<TableManager>();
    to

    Code (CSharp):
    1. tm_script = GameObject.Find("TableGenerator").GetComponent<TableManager>();
    and that solved the problem.

    Thank you to everyone who replied!