Help with beginner code on lesson 27 of the 2d game development course

I’m having trouble understanding exactly what this code does:

var nextStates = state.GetNextStates();

This is what GetNextStates() does:

public State GetNextStates()
{
return nextStates;
}

This is probably really simple, but I’m new to this course.

Hi,

Welcome to our community! :slight_smile:

When we created our State class, we declared a variable named nextStates at the top of our code. In the Inspector, we assigned “next states” to the variable. By having a variable, nothing happens in our project. We must do something with the data.

Our State objects just hold data. Our game logic “happens” in the AdventureGame object. This means that our AdventureGame object somehow needs to access the data in the State objects to be able to display, for example, different story texts or to “know” what “next state” it is supposed to “load”. Since Unity cannot read our mind, we have to explicitely tell it what to do.

The problem we must solve is: Send data from the State object to the AdventureGame class.

And the solution is a method in the State object which returns the reference (“link”) to the “next states” array of our State object. To make the method accessible from other objects, we use the public keyword.

With this in mind, take another look at this method:

public State GetNextStates()
{
    return nextStates;
}

Does it make sense now?


If so, on to this line:

var nextStates = state.GetNextStates();

When reading code with an equal sign, we start reading on the right-handed side.

state.GetNextStates(); means we call the GetNextStates method of the State object which is assigned to the state variable. The method returns a reference (“link”) to an array of State objects. If there is no object reference to return, the returned value is null.

That returned value gets assigned to the nextStates variable, so we will be able to access the array via that variable. Otherwise, we would have to call state.GetNextStates(); all the time, which is a bit hard to read.

Did this clear it up for you?


See also:

1 Like

Thank you for that reply, it cleared things up.

However, I have another question. There must be a reason why the instructors didn’t do this, but why can’t you make [SerializeField] State nextStates inside of State.cs public, instead of putting it inside of a public method? Then back in AdventureGame.cs, wouldn’t you be able to assign a variable to [SerializeField] State nextStates instead of a method that links it?

That’s a good question. Ben and Rick discuss this topic in their video named “Block Breaker Instructor Hangout #2” as of the 9:23 mark.

1 Like

Exactly what I needed to know!

Thank you for finding the exact location where I could find my answer.

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

Privacy & Terms