Adding my two cents.
The declaration is creating a variable of a class of type array, but the variable is empty, is like a glass with a label that says milk, but you haven’t filled it yet. You have to fill the glass and to do that, you have to create a new array of type game object.
I can see how this can be confusing since integers, floats, and booleans don’t need these extra steps, that’s because those aren’t classes or structs, they are primitives.
When creating a variable of any class/struct, you have to set the value in one of these three ways:
- Using the
new
keyword followed by the type and the parameters it needs to be created.
- Assigning it to an already existing variable of the same type.
- Using a method that returns a class/struct of the required type.
I’ll give you an example using a struct you are probably already familiar with, Vector3
.
//.....(1)
Vector3 _myVector3 = new Vector3(0, 2, 0);
//.....(2)
Vector3 _myOtherVector3 = Vector3.up;
//.....(3)
Vector3 _myLateVector3;
private void Awake()
{
_myLateVector3 = CreateRandomVector();
}
private Vector3 CreateRandomVector()
{
float randomValue = Random.Range(-10, 10);
return new Vector3(randomValue, randomValue, randomValue);
}
Vector3.up
, is a static variable inside the Vector3
struct.
Basically, when dealing with classes or structs you have to assign a value to them in a more complex way because they are far more complex than primitive types like floats, ints, and bools.
Hope I didn’t make it more confusing.