Search code examples
c#unity-game-enginegameobject

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

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