- Home /
Camera.main NullReferenceException on Instantiated Character
So, for some reason, my main camera (which is tagged as MainCamera) works fine if the game is run in the editor, but throws a nullreferenceexception when I build and run the game standalone. I can't find anything except "make sure the camera has the Main Camera tag" when looking for solutions. Are there any caveats to using MainCamera on a child of an instantiated object?
I would assume there are. What is the $$anonymous$$ainCamera before you instantiate your object? If it's nothing then there's your problem. If it is something then the problem is probably where you switch it.
I have another camera that is enabled just to show the start menu/an overview of the level. I disable that camera and enable the main. It works fine in the editor, but it doesn't work in the standalone player.
standbyCamera.SetActive(false);
myPlayerGO.transform.FindChild("$$anonymous$$ain Camera").gameObject.SetActive(true);
I set the standbyCamera earlier in the script, but it works because I actually see the scene/menu and am able to interact. As soon as I click start, though, it seems like the $$anonymous$$ain Camera object doesn't get activated.
Am I trying to activate the main camera incorrectly? It seems correct, according to the Unity docs I've read.
$$anonymous$$y first guess would be that FindChild is returning null. Switching main cameras is going to be a hassle no matter how you approach it. I would recommend having the camera prepared beforehand ins$$anonymous$$d of in the prefab.
It has to be in the prefab as I'm instantiating the character on the network.
EDIT: It does seem to work if I leave the main camera on the player character enabled. However, now my mouse look script doesn't want to work. That's a different issue, though. Thanks!
Something has to instantiate the prefab. Whatever that is should be controlling the cameras. If you really really really want the camera inside a prefab then I'd recommend putting a script on your prefab that has a reference to the camera. Then you can get that script using GetComponent ins$$anonymous$$d of wasting time searching.
To switch the main camera: 1) Set the camera's tag to $$anonymous$$ainCamera in the prefab. 1) Load your prefab 2) Destroy or re-tag the current $$anonymous$$ainCamera.
Your answer
![](https://koobas.hobune.stream/wayback/20220613181004im_/https://answers.unity.com/themes/thub/images/avi.jpg)