I am making a paintball gun that fires at wherever the mouse is pointed. I am fairly new to Unity 3D. At present I have an android capsule game object which is a parent to my gun game object which in turn houses my bullet and spawn point. I am struggling with a NullReferenceException which is thrown on line 6 when I attempt to instantiate bullets.
var clone : GameObject = Instantiate (BulletPrefab,
Here is my code which I currently have placed on my bullet
var BulletPrefab :GameObject;
var force : float = 2000;
function Update() {
if(Input.GetButtonDown("Fire1")) {
var clone : GameObject = Instantiate (BulletPrefab,
GameObject.Find("spawnPoint").transform.position,
Quaternion.identity);
clone.rigidbody.AddForce(transform.forward * force);
} }
I can’t work out where I’m going wrong
Thanks,
Louise
I think that your code doesn’t find the “spawnPoint” object that you are searching for.
The best way to avoid NullReferenceException crashes, is to make sure that all your objects that you want to use, actually exists before trying to access their data.
var BulletPrefab : GameObject;
var force : float = 2000;
function Update()
{
if(Input.GetButtonDown("Fire1"))
{
var spawnPoint : GameObject = GameObject.Find("spawnPoint");
var clone : GameObject = null;
if(spawnPoint != null)
{
var spawnPosition : Vector3 = spawnPoint.transform.position;
clone = Instantiate (BulletPrefab, spawnPosition, Quaternion.identity);
}
}
}
The code above is not tested and I’m not used to writing Javascript code, so you might want to rewrite it a little, if its not working. But you see the basic idea of the code.
So before you Instantiate a clone, make sure that the spawnPoint object is actually found, so that you can get its position.
You could do a similar check with your created clone before you try to access its data, just to make sure it really is created by the Instantiate function.
Good luck!