Can I assign no value to a variable like Gamemaker?
Hello, I made a game in Gamemaker. I am trying to make it in Unity.
In Gamemaker, if I wanted to assign no value to a variable, I could assign "noone".
For example, if "attacker" variable has value "noone", it means that no attacker was selected.
In Unity, can I do the same thing to the int variable "attacker"?
Answer by corn · Dec 26, 2019 at 12:37 PM
In C#, there are two different kind of entities you can manipulate: value types and reference types.
In the inspector, null objects will appear as none. But value types, such as integers, are not nullable. By definition, they always have a value. Only reference types (such as a GameObject variable for exemple) can be null.
So in your case, you have two simple solutions:
Replace
int attacker
with any reference type, such asGameObject attacker
orAttacker attacker
(withAttacker
being aSerializable
class of your own) or any other reference type, in which case this variable can be set to nullKeep attacker as an int, but in your code handle
attacker
's value so that a negative value actually means "There is no attacker".int attacker = -1;
is a pretty common convention to indicate "No attacker has been set".