Difference between using a SerializeField and FindObjectOfType

Hi, thanks for the courses! I was wondering what was the difference between the two following methods used at the beginning of this lecture in order to change the properties of Unity objects through scripts:

  1. Using a SerializeField variable of the correct type and then setting this variable to the desired object in Unity.

  2. Using a variable of the correct type and then setting its value to be the desired object with FindObjectOfType in C#.

In the Quiz script, Gary uses the first method to access the TimerImage and the second method to access the Timer. I tried using FindObjectOfType() to access TimerImage in my script but it didnā€™t work, why? Is the image only a component of TimerImage ?

I also tried to use the first method rather than the second one to access my Timer but this time it worked. Is there a particular reason not to do so?

The SerializeField allows us to set the reference in the inspector. FindObjectOfType searches the whole tree (every time it is called) and looks for that type (component) somewhere in the hierarchy. This only works if there is only one object of that type in the hierarchy. If there are more than one, it will only return the first one it finds.

In your code, you were trying to find a type called TimerImage but there is no such type. A type is the name of a class. That is a component. I suspect you named the object in the hierarchy ā€˜TimerImageā€™ and tried to look for that. That will not work, because itā€™s not the name of a type. Gary could use it to find Timer because we created a Timer class (type/component) and now it existed

No, there isnā€™t a reason not to do it like that. If timer exists in the hierarchy when the game is not being played, you can certainly assign it like that. However, if the timer is created via code when the game is running, you donā€™t have something to drag in the inspector so youā€™d have to find it in code.

1 Like

Thanks a lot!
I think I understood my mistakes. I assumed the object of type Timer we were manipulating was the GameObject ā€œTimerā€ when in fact it was the script component attached to it and called Timer as well. I checked by changing the GameObject name and it still works! :slight_smile:

You can search for it by name (itā€™s not recommended because of the performance cost) with

timerImage = GameObject.Find("TimerImage");

It will return the GameObject called ā€˜TimerImageā€™ as long as itā€™s active

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms