Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The Instantiate function for my gun script in Unity is instantiating the bullets as though they were child objects

My gun script Instantiates the bullets as though they were child objects of the gun which causes the bullets to move whenever my gun is moved.

I had been testing the shooting ability of my gun by placing a basic sphere with a rigid body into the bullet gameObject variable. I expected the sphere to simply fall to the ground and nothing. However, when I moved around, the sphere was moving in the same direction that I was. The spheres had been instantiated as the child objects of the muzzle gameobject.

the code for my gunscript is shown below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour
{
    public GameObject bullet;
    public Transform muzzle;
    public int magazineSize;
    public int bulletsInMag;
    public float reloadTime = 3;
    bool reloading = false;
    Quaternion = transform.rot
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0) && bulletsInMag > 0)
        {
            Instantiate(bullet, muzzle);
            Shoot();
        }
        else if ((Input.GetKeyDown(KeyCode.Mouse0) && bulletsInMag <= 0 && !reloading))
        {
            Reload();
        }
    }

    private void Shoot()
    {
        bulletsInMag--;
    }

    private void Reload()
    {
        reloading = true;
        StartCoroutine(ReloadTime());
    }

    IEnumerator ReloadTime()
    {
        yield return new WaitForSeconds(reloadTime);
        bulletsInMag = magazineSize;
        reloading = false;
    }
}

>Solution :

well yes, according to the API Instantiate(bullet, muzzle); will instantiate an instance of bullet as child of muzzle.

You probably rather wanted to use a different overload like for instance

Instantiate(bullet, muzzle.position, muzzle.rotation);

which will rather instantiate the bullet at scene root level but at the same world space position and orientation of muzzle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading