- Home /
Question by
ChaseCodes · Dec 04, 2017 at 02:24 AM ·
gameobjectrigidbodynullreferenceexception
Rigidbody: NullReferenceException: Object reference not set to an instance of an object
my script is when I click the object, the object makes rb.addforce. I am new to C#.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class onClicked : MonoBehaviour {
private Rigidbody rb;
// Use this for initialization
void Start () {
GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
}
void OnMouseDown (){
rb.AddForce (-transform.forward * 500);
}
}
is there a solution? thanks!
Comment
Best Answer
Answer by K43l · Dec 04, 2017 at 02:46 AM
You are getting the Rigidbody component in the Start method, but you don't save it in your variable. You have to write
void Start () {
rb = GetComponent<Rigidbody> ();
}
Small mistake, which happens when you start coding for the first time :D