- Home /
Why does this script instatiates sometimes multiple clones and sometimes not just one?
First, apologise for my bad english. It's not my main language.
So, i wrote a Script witch should shoot a game object and destroy it after a period of time. But the problem is, that if i shoot, it sometimes instantiates multiple game objects and sometimes not even one. If it instantiates just one clone, the doesn't moves if i doesn't push it. If it instantiates multiple clones, the clones are moving like bullets. Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootController : MonoBehaviour {
public GameObject Bullet;
public float lifetime;
public float Velocity;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (Input.GetMouseButtonDown (0)) {
Bullet.GetComponent<Rigidbody> ().AddForce (this.gameObject.transform.forward * Velocity);
print (this.gameObject.transform.forward);
GameObject insbullet = (GameObject)Instantiate (Bullet, this.gameObject.transform.position, Quaternion.identity);
print ("shot");
Destroy (insbullet, lifetime);
}
}
}
Has anyone an idea why this is happening or a solution for this?
Also, please apologise how i have pu tin the c# script, i weren't able to figure out, how to put it in correctly, and i haven't found how to do this in the FAQ section.
Answer by Bunny83 · Aug 24, 2017 at 02:55 PM
Never use any Input.XXXXDown methods inside FixedUpdate. FixedUpdate should only be used for continuous applied forces. The "Down" state of a key is only changed between Update calls. FixedUpdate might be called several times per update or not at all depending on the current framerate.
Just put that code in Update and it should work fine. One time events should always be handled in Update.
Bunny83
In Update it instantiates just one object, but RigidBody.AddForce doesn't works either.
Yes, of course since you use AddFoce on the prefab and not on the newly instantiated object. You should do:
if (Input.Get$$anonymous$$ouseButtonDown (0))
{
GameObject insbullet = (GameObject)Instantiate (Bullet, this.gameObject.transform.position, Quaternion.identity);
insbullet.GetComponent<Rigidbody>().AddForce (transform.forward * Velocity);
Destroy (insbullet, lifetime);
}
Note that "one time forces" should use Force$$anonymous$$ode.Impulse. If you use Force$$anonymous$$ode.Force (which is the default) the force get multiplied by deltaTime which makes no sense for impulse forces.
So you want to use:
AddForce (transform.forward * Velocity, Force$$anonymous$$ode.Impulse);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
how to keep a "ship" over a platform or rigidbody? 0 Answers
Renderer on object disabled after level reload 1 Answer
Cancel out a Addforce && Addtorque? 1 Answer