Declarations / Variables

Hey, trying to understanding declaring variable.
When declaring variables, why do we declare it at the top of our code and then instantiate it later on.
For example at the top of our code we often write;

GameObject[] pool
[SerializeField] int PoolSize = 5;

and then below that in our method we write;

void PopulatePool()
    {      
        pool = new GameObject[PoolSize];
    }
  1. Why do we have to make it a new GameObject when we already declared it to be a Gameobject array at the top?
  2. Why can’t we just write something like GameObject[Poolsize] pool to set the variable. Why do we need to use 2 separate lines of code for this process?

Thanks

Hi,

A variable is not an object. It’s a variable. In our case, pool is “empty” (= null). We have to explicitely assign an object reference.

With new GameObject[PoolSize], we create a new object of type GameObject[]. Then we assign the object reference to pool.

Because C# does not allow us to do that. This would be possible: GameObject[] pool = new GameObject[5];. However, we cannot use any variables at instance level because we cannot guarantee that the variable and its value exist when we try to access it. For this reason, variables can be used within methods only. When we execute method code blocks, the instance variables do exist. Why? Because that’s how C# works.

Is this what you wanted to know? :slight_smile:


See also:

2 Likes

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:

  1. Using the new keyword followed by the type and the parameters it needs to be created.
  2. Assigning it to an already existing variable of the same type.
  3. 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.

We can only assign constant values to any declaration at class level. Since - in most cases - this is not possible for classes and complex structs it is not allowed. We cannot assign variables at class level

int a = 3; // allowed because 3 is constant
int b = a; // not allowed because a is not constant

As long as we are assigning constants, C# will be happy.

public class SillyClass
{
    public int SillyValue { get; set; }
    public static implicit operator SillyClass(int sillyValue) => new SillyClass { SillyValue = sillyValue };
}

SillyClass silly1 = 3; // This is allowed because 3 is constant, even if we are declaring a class

int a = 3;
SillyClass silly2 = a; // Again, this is not allowed because a is not constant

We could initialise the array at class level if we used a constant (Nina mentioned this)

[SerializeField] int PoolSize = 5;
GameObject[] pool = new GameObject[5]; // constant - allowed
// but
GameObject[] pool = new GameObject[PoolSize]; // PoolSize - not allowed
1 Like

Hi Nina, thanks so much for replying. Still wrapping my head around it a bit. Could you please clarify this statement ’ Then we assign the object reference to pool - could you please further explain that relationship?
Thanks again.

Hi Yee, Thank you that is a really great explanation. Even though I am half way through some of the courses I feel like that has not yet been explained properly. Thanks for your time.

Awesome thank you for this. It is all starting to fall into place.

A variable is a container. The object is a separate entity. Regard them as two different things, and the concept will be easier to grasp.

With new GameObject[PoolSize];, we create an object. However, that object exists in memory only, and we do not know where it is. Also, it does not have any name. After we executed new GameObject[PoolSize];, the reference is lost if we do not assign it to a variable. Finding this object again is basically impossible for us.

An object reference is like a link on the internet. You may not remember the URL of a website but maybe you bookmarked the website. Then you could simply click the link and get to the website. Is the link able to exist without the website? Yes, it is. Is the website able to exist without being linked? Yes, it is. For this reason, links and websites are two different things.

The same happens in our code. Our “link” is our variable. Here: pool. Our “website” is our object. Here: new GameObject[PoolSize];. In this specific moment, we generate the object and know the object. We assign the reference (“link”) to our pool variable. When accessing pool, we actually access the object we assigned to it.

1 Like

Thanks Nina, that’s incredibly helpful!

You’re welcome. :slight_smile:

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

Privacy & Terms