Why does checking if Camera.Main is non-null generate an assertion failed message?

I’m trying to add a line in my character controller that checks if the main camera exists, and turns the character relative to that camera:

bool relativeToCamera = true;
if (relativeToCamera && Camera.main !=null)
            relativeTransform = Camera.main.transform;

This works fine while in-game, but every time I quit out of play mode, I get two identical errors pointing at this line: Assertion failed: Assertion failed on expression: ‘go.IsActive() && go.GetTag() != 0’

It specifically points to my conditional check, not the line setting the relative transform, which makes me think that checking if Camera.main !=null is the problem. However, the act of checking whether something is null shouldn’t cause any problems, it’s only trying to access it that would be an issue. Is there something I can change here, or is this one of Unity’s harmless eccentricities?

Hello there,

When you type in “Camera.main”, I’m guessing Unity searches for a Camera with the “main” tag.
But you can’t get the tag of a GameObject that’s inactive, so it gives you an error. Since this only happens when quitting play mode, I am guessing you have that line in an Update loop or OnDestroy call?

An easy fix would be to assign a Camera variable on Start() to “Camera.main”, and then just check if that variable is null or not. That should fix it, but if it doesn’t please let me know.

Hope that helps!