GetComponent vs FindObjectOfType

I have had this happen to me a couple of times now during the course. Must be something I am missing. While adding the Slider timer to the game. When getting a reference to the slider on Start() I use
slider = GetComponent(); and this will return NULL every time.

If I use slider = FindObjectOfType(); then all is well and the code works otherwise as expected.

The object is named Slider and all other names I check appear to be correct. What am I missing?

Is the slider on your current scene? Is your slider public to your script? Your code is saying get the component but you need to specify what component that Unity is suppose to look for. Try GetComponent<SIider>(); GetComponent is more efficient than FindObjectOfType().

Please do not use the backward slash it is the website’s delimiter.

1 Like