user3662189 user3662189 - 3 months ago 7
C# Question

NullReferenceException: Object reference not set to an instance of an object in C#

After the execution of code following exception occurred at the end of code, I have do a lot of changes in the code but nothing change at all.


NullReferenceException: Object reference not set to an instance of an object
RocketController.Start () (at Assets/Script/RocketController.cs:10)


What is the cause of this exception?

using UnityEngine;
using System.Collections;

public class RocketController : MonoBehaviour {

// Use this for initialization
Rigidbody2D rd;
void Start () {

rd.GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update () {

if(Input.GetKey("right"))
{
rd.velocity = new Vector2(1,0);
}
else if(Input.GetKey("left"))
{
rd.velocity = new Vector2(-1,0);
}
else
{
rd.velocity = new Vector2(0,0);
}


}//close update
}

Answer

UPDATE: Here is working code:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody2D))]
public class RocketController : MonoBehaviour {

// Use this for initialization
Rigidbody2D rd;
void Start () {

    rd = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update () {

    if(rd == null)
        return;
    if(Input.GetKey("right"))
    {
        rd.velocity = new Vector2(1,0);
    }
    else if(Input.GetKey("left"))
    {
        rd.velocity = new Vector2(-1,0);
    }
    else
    {
        rd.velocity = new Vector2(0,0);
    }


  }//close update
}
Comments