Answer the question
In order to leave comments, you need to log in
Should I check for null in a getter?
Should I check for null in a getter?
Or is it better to initialize in Awake ()? Just then you will have to receive a variable for each class separately, where initialization in Awake () is needed.
Here is an example:
ExampleClass ec;
public ExampleClass GetExampleClass(){
if(ec == null){
ec = GetComponent<ExampleClass>();
}
return ec;
}
Answer the question
In order to leave comments, you need to log in
Quite a dumb question. It all depends on your internal logic. But - it looks ugly and smacks of design errors - first Init, which does everything GetComponent, and then outside the use of a getter.
Better this way:
And this is only a question about initialization time, similar to Lazy.
If the object is definitely needed, then in Awake(), if there are many such objects and the requested property is not always needed, then it is possible and so, the difference in performance will be insignificant.
ExampleClass ec;
public ExampleClass GetExampleClass
{
get
{
return ec ?? GetComponent<ExampleClass>();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question