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:
static
variable on line 9.Awake()
method at lines 11 through 22 as shown in the following screenshot:An analysis of the code shown in the preceding screenshot is as follows:On the StateManager
class
Line 9: private static StateManager instanceRef;
instanceRef
stores a StateManager
type which is a reference to the StateManager
object in the memorystatic
variableStateManager
Component object that's created will share and see the same valueprivate
so it can't be changed from outside the StateManager
classLine 11: void Awake()
Line 13: if(instanceRef == null)
if
statement is checking whether the instanceRef
already stores a reference to a StateManager
Component object in the memorynull
, meaning no reference is stored, the if
code block is executednull
, meaning there is already a reference to a StateManager
Component in the memory, the else
code block is executedLine 15: instanceRef = this;
StateManager
Component reference stored, this
, which stores a reference to this StateManager
, is assigned to instanceRef
StateManager
Component is created for the first timeLine 16: DontDestroyOnLoad(gameObject);
StateManager
Component is attached to when changing to another Scene levelLine 20: DestroyImmediate(gameObject);
instanceRef
is not null, this second instance needs to be destroyed so that only the original GameManager existsDestroyImmediate(gameObject)
method destroys the second copy that was just created18.119.138.202