- Home /
NullReferenceException: Object reference not set to an instance of an object CannonFire.Update
Hi there, I'm having trouble with getting this to work. My final goal is for the cannonball to be shot towards the cursor, but I though I'd start off just moving it in a direction after spawnging
My C# script:
using UnityEngine; using System.Collections;
public class CannonFire : MonoBehaviour {
public GameObject CannonBall;
public GameObject BallSpawner;
public Vector3 SpawnerPosition;
public Quaternion SpawnerRotation;
public float CannonBallSpeed = 5.0f;
public Vector3 ClickPosition;
// Use this for initialization
void Start () {
SpawnerPosition = BallSpawner.transform.position;
SpawnerRotation = BallSpawner.transform.rotation;
ClickPosition = new Vector3(5, 5, 0);
}
// Update is called once per frame
void Update () {
if( Input.GetMouseButtonDown(0) ) {
Rigidbody Clone;
Clone = Instantiate(CannonBall, transform.position, transform.rotation) as Rigidbody;
Clone.velocity = transform.TransformDirection(new Vector3(CannonBallSpeed, 0, 0));
}
}
}
My error:
NullReferenceException: Object reference not set to an instance of an object CannonFire.Update () (at Assets/Script/CannonFire.cs:33)
I am quite new to this, so be gentle please :P
Are you sure you have a Rigidbody on your CannonBall prefab game object?
The problem here is that the 'CannonBall' prefab is of type 'GameObject', where you need it to be of type 'Rigidbody'. Since the 'as [type]' syntax silently returns null if the type cannot be converted, the error will not occur until the next line, when you actually try to use it.
Alternatively, you could use this line:
Clone = (Instantiate(CannonBall, transform.position, transform.rotation) as GameObject).GetComponent<Rigidbody>();
Thanks for the answers! :)
I actually fixed it by instantiating it as a GameObject and then saying:
Clone.rigibody.velocity = ...
I will give your solution a try as well
Your answer
Follow this Question
Related Questions
Problem for moving an object with a button 0 Answers
NullReferenceException: Object reference not set to an instance of an object 1 Answer
What is wrong with my script? 1 Answer
NullReferenceException: Object reference not set to an instance of an object. 2 Answers
GUI.Drawtexture "nullreferenceexception" 2 Answers