0

I'm trying to make a grenade throwing script but when i test it, it always spawn 2 grenade at the same time.

public class GrenadeThrow : MonoBehaviour {
    public GameObject bulletprefab;
    float speed =20f;
    // Use this for initialization
    void Start () { }

    // Update is called once per frame
    void Update () {
        if (Input.GetButtonUp("Fire1"))
        {
            Camera cam = Camera.main;
            GameObject Grenade = Instantiate(bulletprefab, cam.transform.position + cam.transform.forward, cam.transform.rotation);
            Grenade.GetComponent<Rigidbody>().AddForce(cam.transform.forward * speed, ForceMode.Impulse);
        }
    }
}

1 Answer 1

1

First of all, Input.GetButtonDown is more appropriate for this than Input.GetButtonUp. You can try it and see if Input.GetButtonDown is still what you want.

when i test it, it always spawn 2 grenade at the same time

Assuming that this is the actual code you are using to spawn and throw Objects, then it should work fine.

There two likely problems:

1.The GrenadeThrow script is likely attached to the-same GameObject multiple times.

enter image description here

2.The problem is likely to be that you have your GrenadeThrow script attached to multiple GameObjects. It should only be attached to one GameObject.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

yeah i got it i thrown the script into the character and then accidentally throw another gameobject with the script into the character again
Nice. Figured a duplicate is the problem. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.