We are going to create the StateManager
script and the BeginState
class, then add some code so that we can instantiate BeginState
to make an instance of BeginState
. With the help of the next screenshot, perform the following steps:
Scripts
folder.StateManager
.StateMana
ger
to open it in MonoDevelop.Code
folder and select Add | New Folder.States
.States
folder and select Add | New File.BeginState
.class
file.The following screenshot is the Solution window of MonoDevelop:
With the BeginState
class file open in MonoDevelop, make the changes as shown in the next screenshot:
using UnityEngine;
.namespace Assets.Code.States
. Debug.Log("Constructing BeginState");
.Now the BeginState
class file should look like the following screenshot, except for //Constructor
on line 7 which I added as a visual aid:
Open StateManager
in MonoDevelop, and make the following changes:
using Assets.Code.States;.
private BeginState activeState;
.Start()
method code block, add line 10 activeState = new BeginState();
.Debug.Log("This object is of type: " + activeState);
.The StateManager
class file should look like the following screenshot:
In the Unity script, StateManager
, we are instantiating the BeginState
class and storing a reference of (pointing to in memory) this new BeginState
object in the variable activeState
.
This basic process of creating objects will be used in the State Machine to switch from one State to another State. Instantiating classes is also what Unity is doing when it creates Components.
As an example, in the Scripting Reference, search for and select GameObject. You will see a variable listed named transform
. When you click on Play, Unity instantiates the Transform
class and stores a reference to the Transform
Components object in the transform
variable.
This means that if you need to access the data for a GameObject's Transform
Components, you can simply use the transform
variable instead of having to use the GetComponent<Transform>()
method.
This is exactly the same thing you are doing with the files you just created. The BeginState
is the name of the class file. The activeState
is the name of the variable that will store a reference to the to the BeginState
object created when you click on Play.
18.117.73.127