moshe ralf moshe ralf - 1 month ago 7
C# Question

Why Camera not exist in the script?

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Camera))]
public class CameraFrustumGizmo : MonoBehaviour
{

Camera _camera;

void Start()
{
_camera = GetComponent<Camera>();
}


The Camera is black and when i start to type Ca...there is no Camera.
I'm not getting errors when compiling the script but when running the game i'm getting null exception.

The script is attached to Main Camera.

I tried now this:

using UnityEngine;
using System.Collections;

public class CameraTest : MonoBehaviour {

Camera _camera;

void Start()
{
_camera = GetComponent<Camera>();
}

public virtual void OnDrawGizmos()
{
Matrix4x4 temp = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
if (_camera.orthographic)


Now the Camera exist but once i attached the script to the Main Camera i'm getting null exception before even running the game the null is on the line:

if (_camera.orthographic)



NullReferenceException: Object reference not set to an instance of an object
CameraTest.OnDrawGizmos () (at Assets/MyScripts/CameraTest.cs:17)
UnityEditor.DockArea:OnGUI()

Answer

OnDrawGizmos will be called in the scene view, which means that it may be called while the game isn't running.

Your Start function isn't called until the game runs, so there's a chance that _camera won't be initialized by the time OnDrawGizmos is called.

Basically, when you're messing around with editor scripting, you need to be very careful about which object references exist. It's usually best if your references can be rebuilt on the fly -- given that Unity reloads assemblies each time it re-compiles code, that is going to happen pretty often anyway.

Usually I'll do this with a property that caches a reference the first time it's needed:

Camera cachedCamera;
Camera _camera {
    get {
        if (cachedCamera == null) {
            cachedCamera = GetComponent<Camera>();
        }
        return cachedCamera;
    }
}

That will still fail in some circumstances, but it gives you the basic idea.

Comments