Hello its my very first time working with unity and i’m stuck with but mostly curious about this situation.
so I have one script used for three different other game objects, and I am calling these scripts in another script.
public class balabala : Monobehaviour
{
public GameObject thirdWheel;
public GameObject secondWheel;
public GameObject firstWheel;
private Loading loading1;
private Loading loading2;
private Loading loading3;
void Start()
{
loading1 = firstWheel.GetComponent();
loading2 = secondWheel.GetComponent();
loading3 = thirdWheel.GetComponent();
}
void Update()
{
loading1.restart();
loading2.restart();
loading3.restart();
}
}
THE SCRIPT ABOVE WORKS. So I assumed there is no problem here.
Now I want to have these functions xxxx.restart() only work once inside Start(). but when I move these from Update() into Start(), I have the error Object reference not set to an instance of an object.
So my question is why and how to I solve it. Thanks
It would be helpful if you included the entire error message but I’m going to take a guess as to what’s happening here:
The code in restart() is dependent on something that happens in the Loading method’s Start method. So inside the Loading script, you have a Start method and it’s doing some kind of initialization, maybe like a GetComponent call or something to assign a variable.
The problem is that in Unity, the order in which the Start() methods of different scripts run in is essentially random. So what’s happening is that balabala.Start() is running BEFORE Loading.Start(). That means if you try to call restart() inside balabala.Start(), your Loading script is not yet initialized, and you get the error.
One quick way to fix this is to move that code that is currently in Loading.Start() into Loading.Awake(). Awake always runs before start.
1 Like
Thanks you so much Praetor, this really helped me understand the situation.
I’ve gotta say I don’t think I would have ever figured that our myself, as this completely lies in the Loading script.
Also sorry for not posting the entire error, but you did a great guessing. Thank you again.
I’d like to add a question, is it a good practice to add all these get components inside awake() instead of start()?
Yes normally you do initialization such as GetComponent caching in Awake for this exact reason.
1 Like
what if you initialize in awake, but the function you call in start still throws the null reference error?
If it’s initialized in Awake it’ll be available in Start, so probably the error lies elsewhere. A forgotten inspector assignment, or a failed GetComponent, or the reference was never assigned a value maybe.
If you make your own thread, copy/paste the code using the forum’s code tags along with the error code, and I’m sure someone will help you figure it out rather than dicussing in an old thread 
1 Like