- Home /
Gunfire Help
I am using this code:
var projectile : GameObject;
var speed = 50;
var fireRate = 0.11;
private var lastShot = -10.0;
function Update ()
{
if(Input.GetButtonDown("Fire1")){
if(Time.time > fireRate+lastShot){
clone = gameObject;
Instantiate(projectile, transform.position, transform.rotation);
projectile.tag = "Bullet";
clone.gameObject.AddForce(transform.forward * speed);
lastShot = Time.time;
}
Destroy(clone.Bullet, 3);
}
}
And when I try to fire a bullet in the game, it says: "UnassignedReferenceException: The variable projectile of 'gunfire' has not been assigned."
What am I doing wrong?
Answer by Berenger · Mar 12, 2012 at 01:03 AM
There is three mistakes. The most important one is "clone =gameObject;". You're affecting the reference of the gameObject this script is attached to to the variable clone. You should do "clone = Instantiate(projectile, transform.position, transform.rotation); " instead
Secondly, You need the rigidbody to use AddForce. I don't know why the compiler isn't shouting at you.
Finally, you're are destroying the clone even when it's not instantiated, due to fireRate+lastShot timer. This might by secured by Unity, but in any cases it should be inside the scope where there is the instantiation.
Your answer
![](https://koobas.hobune.stream/wayback/20220613065012im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
RayCast Shooting not working 0 Answers
varification error in editor script 1 Answer
Wall Issue 1 Answer