Firing a bullet from a gun

I know this has been asked countless times already, but I’m having difficulty managing this. I’ve tried following various suggestions/threads on the subject and even this tutorial…

…but I can’t get it working properly. With that tutorial, the bullet/projectile doesn’t even appear. If I use my Raycast to detect whether something has been hit, it ends up detecting/hitting the player instead. I’ve commented all of that out though and just used an OnTriggerEnter like from the tutorial, but it still doesn’t show. I’ve been trying for hours with various ways and gotten no where. :-\

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

public class RayGun : MonoBehaviour
{
    public GameObject projectilePrefab;
    public Transform projectileSpawn;
    public float projectileSpeed = 30f;
    public float lifeTime = 3f;

    void Start()
    {
       
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Fire();
        }
    }

    private void Fire()
    {
        GameObject projectile = Instantiate(projectilePrefab);
        Physics.IgnoreCollision(projectile.GetComponent<Collider>(), projectileSpawn.parent.GetComponent<Collider>());
        projectile.transform.position = projectileSpawn.position;
        Vector3 rotation = projectile.transform.rotation.eulerAngles;
        projectile.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);
        projectile.GetComponent<Rigidbody>().AddForce(projectileSpawn.forward * projectileSpeed, ForceMode.Impulse);
        StartCoroutine("DestroyProjectile");
    }

    private IEnumerator DestroyProjectile (GameObject projectile, float delay)
    {
        yield return new WaitForSeconds(delay);
        Destroy(projectile);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HurtEnemy : MonoBehaviour
{
    public int damnageToGive = 10;
    public float range;
    public ParticleSystem projectileEffect;

    private void OnTriggerEnter(Collider other)
    {
        print("hit " + other.name + "!");
        Destroy(gameObject);
    }

    //Physics such as Raycasts are better within the FixedUpdate function as it runs in tandem with the physics
    /*public void FixedUpdate()
    {
        projectileEffect.Play();
        RaycastHit hit;
        if(Physics.Raycast(transform.position, transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name);
            EnemyController target = hit.transform.GetComponent<EnemyController>();
            if(target != null)
            {
                target.Damage(damnageToGive);
            }
        }
    }*/
}

Can you see the projectile in the Hierarchy panel, at least?

Yeah. But it isn’t even hitting an enemy either.

It looks like the projectile object is in the scene, and if I fire, though I can’t see any bullets fire, something is still hitting the projectile that’s there and destroying it.

I’ve even tried following this one. Same problem - no projectile. :frowning:

seems like you hit your own collider

  • you are making 3d right? not 2d…?
    p.s. i think your bullet is not parented to player so you don’t ignore physics by saying .tranform.parent…

Yeah. Which is strange as this bit of code was supposed to prevent that from happening:

Physics.IgnoreCollision(projectile.GetComponent<Collider>(), projectileSpawn.parent.GetComponent<Collider>());

Then again, the parent is probably my gun and not the character. The gun is a child of one of my character’s hands.

i think your bullet is not parented to player so you don’t ignore physics by saying projectileSpawn.parent.GetComponent()
I think insantiate just puts it into scene… so it doesn’t have parent

Though I need to avoid parenting my bullet to the player/gun. I did that before. I need it to fire independently as it doesn’t work correctly when I try to use two animation layers and an avatar mask so I can shoot and walk at the same time.

well yeah i think you should avoid that,
but what you could try is, in bullet at:

private void OnTriggerEnter(Collider other)
    {
        print("hit " + other.name + "!");
        Destroy(gameObject);
    }

change to this

private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player") {
            return;
        }
        print("hit " + other.name + "!");
        Destroy(gameObject);
    }

just for testing, and make player tagged Player

I’ve changed a lot of code around now that it’s no longer hitting the player, but comes up with ‘Object reference not set to an instance of an object’ on the Physics.IgnoreCollision(projectile.GetComponent<Collider>(), projectileSpawn.parent.GetComponent<Collider>()); line.

is your projectileSpawn set up in inspector?
you can see the setup in hiearchy right? so you can count the number of parent to get to player, because you said gun is child of hands which i presume are child of player so you should try

Physics.IgnoreCollision(projectile.GetComponent<Collider>(), projectileSpawn.parent.parent.GetComponent<Collider>());

Okay, so now, after trying that, the projectile is instantiating in the scene, but it’s appearing outside. If I move it in the player’s path, it gets destroyed and says ‘hit Player’. Nor are they being destroyed via the Coroutine.

outside of what? + i think the coroutine never worked, you could just write
Destroy (projectile, 2f); instead of startcoroutine in fire method. this will destroy it after 2 seconds.

Outside of the scene/the camera’s view. I’ve sorted it though - it was my original prefab’s position. I’ve set up a new one. Okay, I’ll give that a go. Usually I’ve had no problems with Coroutines, so it’s strange how it wasn’t being called.

To be honest, I’m starting to think with the way my character, gun and animations are set up, I don’t think any traditional method of firing a bullet is going to work. When Space is down, there’s a slight delay before the fire animation plays. The gun object is set to inactive for the other animations, but is active in my Attack animation and it plays. But then it quickly deactivates after it’s finished. With the delay and how it becomes active and inactive, it makes the projectiles appear in different places each time. The Raycast line I got showing when I had that set up made the line flicker in different places every frame.

there is also this tut
https://www.youtube.com/watch?v=THnivyG0Mvo

in which you dont spawn no bullets but just a little particle effect at hit point and it’s instant over range, but of course you could add a setup that could depend on distance and give a slight delay and offset as wind or something and perhaps add some tracers at the barrel so it looks like its actually shooting projectiles…

Yeah, Brackey’s tutorial was the first one I used. :slight_smile: His tutorials have been very useful. I guess that’s what I’ll have to do in this case. Shame, as I would have liked to have figured out a good way of firing actual bullets/projectiles. How do other Unity devs manage when different animation states are played, such as attack? Are their weapons usually part of the firing animation? Or do they attach the weapon as a child to the character’s hand and toggle it on/off?

i never did something with shooting projectiles from firearms and animations so i don’t know.
but i think they stop the animation that is not “shoot” and just play “shoot” if thats what you mean

Well, thanks for your help anyway. :slight_smile:

is your game 3d first person?