- Home /
Do I have to check for null value before assigning a variable in Awake()?
I have a code written as the following
void Awake()
{
if(this.robot == null)
this.robot = GameObject.FindObjectOfType<Robot>()as Robot;
else {
this.robot = null;
this.robot = GameObject.FindObjectOfType<Robot>()as Robot;
}
}
Since this is happening in Awake()
, is null checking necessary? Can't it be written as the following?
void Awake()
{
this.robot = GameObject.FindObjectOfType<Robot>()as Robot;
}
EDIT:
I am not accessing robot's properties or methods in the Awake().
You can use the second. The null checking is unnecessary.
Answer by Trungdv · Dec 03, 2014 at 12:31 AM
Null checking is not necessary, because you do not read value of "robot" at all.
Not in Awake()
, no. But I access it later in the Start()
.
Null checking is only useful immediately before you read a value. There is no benefit to check if a value is null immediately before writing to it.
The only exception to this rule is if assigning the value has side effects. Having side effects that require null checking by the user before assigning a value is bad coding practice, and should be avoided.
Your answer
Follow this Question
Related Questions
XMLDocument GetElementByID returning null 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Camera Controls Need Help 1 Answer