- Home /
NullRefenceException error
So I get "NullReferenceException: Object reference not set to an instance of an object" at this line camera3rd.enabled=false;
. Can't figure out what's wrong
using UnityEngine;
using System.Collections;
public class CameraSwitch : MonoBehaviour {
public SmoothFollow camera3rd;
public Transform target;
public float time;
void Start () {
// Auto setup smoothfollow to a cameraswitch script
camera3rd = gameObject.GetComponent<SmoothFollow>() ;
//disabling this script
camera3rd.enabled=false;
}
Have a look at my explanation on null reference exceptions and how to fix them. You can find it here.
Answer by mattyman174 · Feb 22, 2014 at 11:11 AM
public SmoothFollow camera3rd;
This is an uninitialized variable, did you forget to add a SmoothFollow script component to the GameObject?
Are you positive. I have a test script setup exactly like yours and i can compile and run it fine, it does as expected.
Can you copy and paste the exact error message please.
NullReferenceException: Object reference not set to an instance of an object CameraSwitch.Start () (at Assets/SwitchCameras/CameraSwitch.cs:18)
@diablia: I guess then you have drag&dropped it correctly in the inspector, but when you call gameObject.GetComponent< SmoothFollow >()
, it doesn't find it and "resets" the camera3rd
variable to null
?
Double check that you do have both scripts attached to the same GameObject as components.
You should have at least a CameraSwitch Script Component and an SmoothFollow Script Component attached to the GameObject.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
[Solved]NullReferenceException problem 2 Answers
Distribute terrain in zones 3 Answers
NullReferenceException .. problem with Camera.main.transform 2 Answers