We are going to instantiate the BeginState
class to create an instance object in the memory. This will demonstrate how objects are created. Before we can do this, we first need to attach the StateManager
script to a GameObject. To do so, perform the following steps:
StateManager
script to the Main Camera GameObject.The BeginState()
method in the BeginState
class is a special method known as a constructor. It serves the same purpose as the Start()
method or the Awake()
method in a Unity script to initialize any member variables in the instance object created.
activeState
variable is a reference to an instance object of the BeginState
class.The following is the code analysis on various classes:
An analysis of the code shown in the preceding code screenshot is as follows: On StateManager
class
Line 6: private BeginState activeState;
activeState
is a variable that can store a reference to an object of type BeginState
activeState
variable is private because you don't want any external code to change the stored valueLine 10: activeState = new BeginState();
new
operator is how you create an instance of a classBeginState
has been created in memoryBeginState
classAn analysis of the code shown in the preceding code screenshot is as follows:On BeginState
class
Line 7: public BeginState()
BeginState
classLine 9: Debug.Log("Constructing BeginState");
StateManager
line 10An analysis of the code shown in the preceding code screenshot is as follows:On StateManager
class
Line 10: activeState = new BeginState();
BeginState
instance object is assigned to the variable activeState
Line 11: Debug.Log("This object is of type: " + activeState);
Earlier you changed line 3 in BeginState
. What is this namespace
on line 3?
If you look up namespace on the Internet, you might be overwhelmed with explanations. For writing classes in Unity, I'll boil it down to this:
For coding in the Unity environment, that's really all you need to know.
The BeginState
file is in the States
folder, which is a subfolder of the Code
folder, which in turn is a subfolder of the Assets
folder. It's a lot easier to use the Dot Syntax to express this location like this: Assets.Code.States
. Therefore, line 3 declares this, and the whole BeginState
class definition is in the namespace
code block.
Now that this location has been declared in BeginState
, any other class that wants to use BeginState
has to specify this same location, otherwise it won't be found.
18.117.99.71