Object reference not set to an instance of an object

Hey there,

I have two C# scripts; one is a throttle lever (throttlelever.cs) that when clicked, should be triggering an iTween animation; the object to activate being given (caraccelerate.cs).

My error is

NullReferenceException: Object reference not set to an instance of an object
throttlehover.OnMouseDown () (at Assets/throttlehover.cs:17)
UnityEngine.SendMouseEvents:DoSendMouseEvents()

I’m Guessing they can’t find one another, but I hope someone will be able to enlighten me on why that is.

My throttle script:

using UnityEngine;
using System.Collections;

public class throttlehover : MonoBehaviour
{
    public caraccelerate accelerate;
    void OnMouseEnter ()
    {
        renderer.material.color = Color.red;    
    }
    void OnMouseExit ()
    {
        renderer.material.color = Color.white;    
    }
    void OnMouseDown ()
    {
        accelerate.OnAccelerate();
    }
    
}

My caraccelerate vehicle script:

using UnityEngine;
using System.Collections;

public class caraccelerate : MonoBehaviour
{

public void OnAccelerate ()
    {
        iTween.MoveTo(gameObject, iTween.Hash("path", iTweenPath.GetPath("centralline"), "time", 50, "easetype", iTween.EaseType.easeInOutSine));
    }

}

Kind regards,

It sounds like you didn’t assign anything to your accelerate variable. In the inspector since your accelerate variable is public you can just drag and drop the caraccelerate gameobject into that variable.

Or in your start method in the throttle script you can put something like

accelerate = GameObject.FindObjectOfType(typeof(caraccelerate)) as caraccelerate;

which will find a reference to a game object with a caraccelerate component on it and assign it to accelerate. (warning if there are more than one caraccelerate gameobjects it may not assign the correct one to your object)

So, basically your problem is your accelerate variable is empty/null and you need to assign it a caraccelerate reference.

Thanks guys! i was able to actually drag the caraccelerate (vehicle) from the Hierachy onto the Throttle script in the inspector and it did pretty much the same thing.

Kind regards,