There is a bit more to know about C#: value types and reference types. Value types are never null.
For example, when you declare int number;
, the value of number
will be 0 because the default value of int is 0. There are just a handful of value types, so I’d suggest to learn them by heart. Everything else is a reference type.
FindObjectOfType returns the “first” object of a type it finds. For this reason, we use it only if we have just one object of that type in our scene or if we do not look for a specific object.
Here is a “bad” example of how you could find different components:
ScoreBoard sb1 = GameObject.Find("Player").GetComponent<ScoreBoard>();
ScoreBoard sb2 = GameObject.Find("Score Board").GetComponent<ScoreBoard>();
The ScoreBoard component must be assigned to a game object named Player and to a game object named Score Board. Otherwise, you’ll get null
returned.
That’s a fairly clumsy example because of the hard-coded strings and the slow Find methods.
If we know the component before we start the game, we could assign the reference ourselves in the inspector. We would use [SerializeField], which was covered in the Project Boost section. That’s how we typically “link” things in Unity.