Camera.main NullReferenceException, Camera.main performance

At run time, Unity generates an error at the line: Camera.main. Found that "Camera.main" is NULL.

The error message is: NullReferenceException: Object reference not set to an instance of an object...

Please note that only have 1 camera for the whole game project.

"Main Camera" is already enabled and tagged as "Main Camera" automatically by Unity.

If it still thinks that "Camera.Main" is null, You can use this:

"GameObject.Find("NameOfCameraGameObject").GetComponent();"

The first enabled camera tagged "MainCamera" (Read Only).

Camera.main is Slow

Camera.main takes more time to execute than you might expect. If you use it many times per game loop, you will be wasting time unnecessarily.

You should store a reference to each of your Cameras once in the lifetime of that Camera, and then use that stored reference in the rest of the code. For example:

// Initialization code for scene

Camera mainCamera = Camera.main;

// Game code, executed once per frame or more

Vector3 pos = mainCamera.transform.position;

Camera.main returns the first Camera in the scene tagged "MainCamera", so it may be slower if you have additional Cameras that are tagged differently. Even for a single Camera, the tag checking means it will always be slower than a direct reference.

The primary Camera in the scene. Returns null if there is no such camera in the scene. This property uses FindGameObjectsWithTag internally and doesn't cache the result. It is advised to cache the return value of Camera.main if it is used multiple times per frame.

猜你喜欢

转载自avi.iteye.com/blog/2403875