- Home /
how to create a gun in unity3d
can someone please help im trying to make a gun shoot but it says NullRefenceExeption for this line
var bullet = Instantiate(BulletPrefab,
PLEASE HELP ME
Answer by Hybris · Feb 26, 2012 at 08:44 AM
Hello massman,
I have problems with it as well, Unity is a little weird the code should be for example:
var bullet = Instantiate(BulletPrefab, transform.position, transform.rotation);
If that doesn't work you have to do it the long way around:
var bullet : Rigidbody;
bullet = Instantiate(BulletPrefab, transform.position, transform.rotation);
I don't know if you already added a force to the bullet but here is the code(fast and short):
bullet.rigidbody.AddForce(//force and stuff);
but I dont like this method I like to use transform.TransformDirection:
bullet.transform.TransformDirection(Vector3.forward) * Force;
//force being you force variable or just a number.
When you are using Vector3.forward, remember Vector3.forward is 0,0,1. Keep that in mind when multiplying.
Grz, Hybris
Answer by scipiothegreat · Feb 27, 2012 at 02:24 AM
If that is the entire line, then it just needs to be completed. At the top of the script, outside of any functions, are where variables are defined. In this area, you should add something like
var bulletPrefab : gameObject;
In the Inspector drag the prefab you want from Project View onto the empty variable. To launch it, you need to instantiate it, and then give it a velocity, assuming it has a rigidbody attached.
var bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.rigidbody.AddForce(bullet.transform.forward*100);
I could be wrong but, I think transform.forward doesnt exist, and that you dont have to include the bullet part.