- Home /
Need help with bullet/gun scripting
Hi!! Im new to unity. I have my gun script, spawn point, bullet, and gun. heres my script.
var Bullet: Transform; function Update () { if (Input.GetButtonDown ("Fire1")){
var bullet=Instantiate(Bullet,GameObject.Find("Gun_Spawn").transform.position,Quaternion.identity); bullet.rigidbody.AddForce(transform.forward *2000);
}
} but every time I hit Fire1 (Left mouse) the bar at the bottom of the screen says, Theres no rigidbody attached to clone, script still searching?? I dont know what to do?? and I also need a script to destroy the bullet. Can any body help?? Thank you for the time.
one question per post but in answer to your destroy question http://lmgtfy.com/?q=unity3d+destroy+gameobject
Answer by Marnix · Apr 13, 2011 at 05:22 PM
You are saying: bullet.rigidbody
. But the bullet doesn't have one. Unity3D throws you a NullReferenceException
. To solve this: add a new RigidBody component.
If your bullet is a prefab, you can just add it in your editor.
If it is a class that you are creating from code somehow, use a script:
bullet.addComponent(new RigidBody());
will probably work.
Answer by AngryOldMan · Apr 13, 2011 at 05:19 PM
well logic would dictate that you should add a rigidbody component to the prefab that your script is trying to instantiate
Answer by Kourosh · Apr 13, 2011 at 05:23 PM
The problem is that your bullet prefab does not have rigidbody attached.
just to remind you also in unity variables should be started with small letters.
why should unity variables be named with small letters? I have loads of codes with variables with a number of case differences in them and it doesnt make a difference to how they perform
Sorry i meant it's better to start variables with small letter. It's not that it won't work if you use Upper case, it's just a scripting discipline so they are not mistaken with functions which are usually started with Upper case. here is what i found: http://forum.unity3d.com/threads/6903-Is-there-a-recommended-na$$anonymous$$g-convention
and also wherever i checked in unity's scripting manual you'll see the same rule being applied.