What does this exclamation mark mean before Instance?

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

1 Like

In words:
If there is no GameManager Instance (meaning its null) then assign the one who has that script to it.

1 Like

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

3 Likes

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.

2 Likes