- Home /
Order scripts execute "start" or order of "update" every frame, c# mainly
I have 2 scripts,a utility script that is meant to list all gameobjects that might be used by others (to avoid lots of searches) and a script that wants to use this script and use a gameObject's script component reference.
I have both of my code in start, but when i check the inspector the utility script finds the gameobjects fine, but my 2nd script cannot access them. I try to set a variable to the object reference from my utility script and it shows up as null in inspector. The utility script has this reference fine. When i move the assignment statement to "update" it successfully finds the reference and assigns it from the utility script.
This makes me believe that my start method for my 2nd script is running before my utility script gets a reference. How do i change in what order these two scripts execute so that all my scripts can fetch object references from the utility script AFTER utility script is done executing, and hence avoid null references?
If you need more info just ask. I hope i gave enough. PS: My script code to locate the utility script works fine, just returns null when it is in "start" method.
Answer by Llama Fragments · Jul 07, 2012 at 12:56 AM
Try changing the execution order of your scripts so that the utility script runs first, pretty sure that's under Edit/Project Settings/Script Execution Order
Answer by Moohasha · Jul 07, 2012 at 12:27 AM
I don't think you can control the order in which scripts start or are updated, though you can to some degree by using Update(), FixedUpdate(), and LateUpdate() appropriately. In your case, I would have a method in the utility script to return the list of GameObjects rather than just making the list public, and the first time that method is called you do the initial look up and populate the list that is then returned later. Then, in your utility script's Start method(), call this method to make sure it gets initialized. However, if your other script happens to start up and call this method first, you're still guaranteeing that the list gets populated.
Seems a convoluted work around. But the script execution order menu is super useful. They need to advertise this and make it easier to get to, and easier to select scripts in a certain folder. (Right now it shows ALL scripts in assets folder, even extensions to unity or frameworks i have added)