canvasGroup is null in Fader.cs

Sorry for bothering you. I had read the previous topic about null in fader that that guy had exactly the same problem as me. I had read the solution, but somehow i put everything in Awake function from the beginning and this solution still didnt work for me.

Thank a lot.

That is strange, as it’s almost impossible to get to FadeOutImmediate() before Awake()… That being said, it is truly “almost”.

Let’s make FadeOutImmediate a little more bulletproof:

public void FadeOutImmediate()
     if(canvasGroup==null) canvasGroup = GetComponent<CanvasGroup>();
     canvasGroup.alpha = 1;

I just thought that maybe GetComponent<CanvasGroup>() isn’t finding a CanvasGroup on the game object which would then still give the same error here. Suspect there is either no CanvasGroup or it’s not on the same object. Only if the error persists

Based on the logs, the OP isn’t getting errors on FadeIn and FadeOut, meaning the CanvasGroup was found by the time those methods ran.


This is weird. The command that contains null value was called before awake as i put 2 debug commands in awake function that find CanvasGroup and the null-contain function. On the other hand, checking null make it work.

There is actually one condition that could cause this race condtion, and that is if the SavingWrapper is calling FadeOutImmediate() in Awake() instead of Start() (Because if SavingWrapper gets it’s Awake() done before Fader does, then CanvasGroup won’t be set properly.
In any event, null checking is, short of a quick and dirty Lazy, an ideal solution.

Bonus: Quick and dirty Lazy evaluation:

CanvasGroup _canvasGroup; //Do not refer to this in code
CanvasGroup canvasGroup //Always refer to this one
          if(_canvasGroup==null) _canvasGroup = GetComponent<CanvasGroup>();
          return _canvasGroup;

With this setup, you effectively prevent any possible race condition, as any call to canvasGroup ensures that the backing field _canvasGroup will exist before the canvasGroup property is completely evaluated. With this, you can take both checks out, both in Awake() and FadeOutImmediate. (In fact, you’ll have to, they won’t compile as canvasGroup cannot be set outside of the property itself).

Privacy & Terms