I marked in red to locate what I want to understand:
public static GameManager Instance;
private void Awake()
{
if (!Instance)
{
Instance = this;
}
}
I marked in red to locate what I want to understand:
public static GameManager Instance;
private void Awake()
{
if (!Instance)
{
Instance = this;
}
}
it means if the instance is null,
if it doesnât exist
In words:
If there is no GameManager Instance (meaning its null) then assign the one who has that script to it.
Itâs known as the âlogical negation operatorâ:
In short hand most developers will read it as the ânot operatorâ.
The phrase:
if (!x)
Can be read: if not x
The not operator expects a boolean after it. So x should be a boolean (or in your case âInstanceâ). If itâs not a boolean, than it needs to be able to be implicitly converted to a boolen, or define the ! operator as one of its own (which will behave however you implemented that).
In the case of the above, Instance is a âGameManagerâ. Likely âGameManagerâ inherits from MonoBehaviour or the ilk. In which case Unity has created an implicit conversion to boolean. If the object is destroyed/null, it converts to false, and if itâs alive and well it converts to true.
So you can say:
if(Instance)
And it means: if instance is alive
or, the code in question:
if(!Instance)
And it reads: if instance is not alive and well
Means basically the same thing as
if (Instance == false)
but since the object probably just reports true/false based on if it is destroyed/null or not, what youâre really checking for probably means this
if (Instance == null)
Which is how I usually write it, even though the shorthand saves a few keystrokes.