Time for action – adding the Awake method to StateManager

In the code block of the Awake() method, we're going to check if the GameManager GameObject already exists. If it doesn't, we'll save it to a variable and tell Unity not to destroy it when any other Scene level is loaded. If it does already exist, we'll tell Unity to destroy any new GameManager GameObjects created.

Insert the new code as shown in the following steps:

  1. Add a new static variable on line 9.
  2. Add the Awake() method at lines 11 through 22 as shown in the following screenshot:
    Time for action – adding the Awake method to StateManager

What just happened?

An analysis of the code shown in the preceding screenshot is as follows:On the StateManager class

Line 9: private static StateManager instanceRef;

  • This variable named instanceRef stores a StateManager type which is a reference to the StateManager object in the memory
  • This is also a static variable
  • This means, that in this example, each instance of the StateManager Component object that's created will share and see the same value
  • It is private so it can't be changed from outside the StateManager class

Line 11: void Awake()

  • Unity calls the Awake() method once after all objects in the game are loaded into memory, and before the game actually plays

Line 13: if(instanceRef == null)

  • This if statement is checking whether the instanceRef already stores a reference to a StateManager Component object in the memory
  • If the value is equal to null, meaning no reference is stored, the if code block is executed
  • If the value is not null, meaning there is already a reference to a StateManager Component in the memory, the else code block is executed

Line 15: instanceRef = this;

  • Since there's no StateManager Component reference stored, this, which stores a reference to this StateManager, is assigned to instanceRef
  • This will be the case when the game has just started and the StateManager Component is created for the first time

Line 16: DontDestroyOnLoad(gameObject);

  • This method tells Unity to not destroy the GameManager GameObject, which the StateManager Component is attached to when changing to another Scene level

Line 20: DestroyImmediate(gameObject);

  • When BeginningScene is reloaded, another GameManager GameObject is created
  • Since instanceRef is not null, this second instance needs to be destroyed so that only the original GameManager exists
  • The DestroyImmediate(gameObject) method destroys the second copy that was just created

Changing the Scenes

Now let's write the code that will change from BeginningScene to Scene1, and back to BeginningScene.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.138.202