Help with a bonus measure to stop false triggers for some code

I have some code to respawn the player and after a couple deaths, send them to main menu, issue is that sometimes it just triggers a false death and sometimes sends me to the main menu, this mainly happens when firing my gun and walking at the same time, the bullets it fires does not have the enemy tag. I would just like some help doing an extra measure to make this not happen. I will send the code.

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

public class KillFloor : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawn_point;

    bool dead;

    private Rigidbody playerRigidbody;

    public int lifesAmount;

    int lifesLeft, lifesLost;

    private void Awake()
    {
        lifesLeft = lifesAmount;
        dead = false;
    }

    private void Start()
    {
       

        playerRigidbody = player.GetComponent<Rigidbody>();
        
    }

    private void OnTriggerEnter(Collider other)
    {
       

        if (other.gameObject.CompareTag("Enemy"))
        {
           

            if (playerRigidbody != null)
            {
                
                playerRigidbody.position = respawn_point.position;
                playerRigidbody.velocity = Vector3.zero; // Reset velocity to avoid unwanted movement
                lifesLeft--;
                lifesLost++;
                dead = true;
            }
            else
            {
               
                player.transform.position = respawn_point.position;
                lifesLeft--;
                lifesLost++;
                dead = true;
            }

        }
    }

    private void Update()
    {
        Input();
    }

    private void Input()
    {

        if (dead = true && lifesLeft > 0)
        {
            dead = false;
            
        }

        if (dead = true && lifesLeft < 0)
        {
            Debug.Log("Died");
            Killed();
        }
    }

    private void Killed()
    {
        SceneManager.LoadScene("Menu");
    }
}

Now the gun and bullet code if any eagle eyes spot something that may trigger it. (projectile is gun and bullet is bullet.)

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

public class Projectile : MonoBehaviour
{
    public GameObject bullet;

    public float shootForce, upwardsForce;

    public float timeBetweenShooting, spread, reloadTime, timeBetweenShots;
    public int magazineSize, bulletsPerTap;
    public bool allowButtonHold;

    int bulletsLeft, bulletsShot;

    public Rigidbody playerRb;
    public float recoilForce;

    bool shooting, readyToShoot, reloading;

    bool shooting2, readyToShoot2, reloading2;

    public Camera cam;
    public Transform attackPoint;

    public GameObject muzzleFlash;
    public TextMeshProUGUI ammunitionDisplay;

    public bool allowInvoke = true;

    private void Awake()
    {
        bulletsLeft = magazineSize;
        readyToShoot = true;
    }
    void Start()
    {
        
    }

    
    void Update()
    {
        MyInput();

        if (ammunitionDisplay != null)
            ammunitionDisplay.SetText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap);

    }



    private void MyInput()
    {
        if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
        else shooting = Input.GetKeyDown(KeyCode.Mouse0);


        if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();

        if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();

        if(readyToShoot && shooting && !reloading && bulletsLeft > 0)
        {
            bulletsShot = 0;

            Shoot();
        }

        if (allowButtonHold) shooting2 = Input.GetKey(KeyCode.Joystick1Button5);
        else shooting2 = Input.GetKeyDown(KeyCode.Joystick1Button5);

        if (Input.GetKeyDown(KeyCode.Joystick1Button1) && bulletsLeft < magazineSize && !reloading2) Reload();

        if (readyToShoot2 && shooting2 && !reloading2 && bulletsLeft <= 0) Reload();

        if (readyToShoot2 && shooting2 && !reloading2 && bulletsLeft > 0)
        {
            bulletsShot = 0;

            Shoot();
        }
    }

    private void Shoot()
    {
        readyToShoot = false;

        readyToShoot2 = false;

        Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;

        // Calculating how far the gun is from the middle of screen then making it fix the angle it fires at.

        Vector3 targetPoint;
        if (Physics.Raycast(ray, out hit))
            targetPoint = hit.point;

        else
            targetPoint = ray.GetPoint(75);

        Vector3 directionWithoutSpread = targetPoint - attackPoint.position;

        float x = Random.Range(-spread, spread);
        float y = Random.Range(-spread, spread);

        Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0);
        
        GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
        currentBullet.transform.position = directionWithSpread.normalized;

        currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
        currentBullet.GetComponent<Rigidbody>().AddForce(cam.transform.up * upwardsForce, ForceMode.Impulse);





        if (muzzleFlash != null)
            Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);

        bulletsLeft--;
        bulletsShot++;

        if(allowInvoke)
        {
            Invoke("ResetShot", timeBetweenShooting);
            allowInvoke = false;

            playerRb.AddForce(-directionWithSpread.normalized * recoilForce, ForceMode.Impulse);
        }


        if (bulletsShot < bulletsPerTap && bulletsLeft > 0)
            Invoke("Shoot", timeBetweenShots);
    }





    private void ResetShot()
    {
        readyToShoot = true;
        readyToShoot2 = true;
        allowInvoke = true;
    }


    private void Reload()
    {
        reloading = true;
        Invoke("ReloadFinished", reloadTime);
        reloading2 = true;
        Invoke("ReloadFinished", reloadTime);
    }
    private void ReloadFinished()
    {
        bulletsLeft = magazineSize;
        reloading = false;
        reloading2 = false;
    }    

}

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

public class Bullet : MonoBehaviour
{
    public Rigidbody rb;
    public GameObject explosion;
    public LayerMask whatIsEnemies;

    [Range(0f, 1f)]
    public float bounciness;
    public bool useGravity;

    public int explosionDamage;
    public float explosionRange;
    public float explosionForce;

    public int damage;

    public int maxCollisions;
    public float maxLifetime;
    public bool explodeOnTouch = true;

    int collisions;
    PhysicMaterial physics_mat;


    private void Start()
    {
        Setup();

    }

    void Update()
    {
        if (collisions > maxCollisions) Explode();

        maxLifetime -= Time.deltaTime;
        if (maxLifetime <= 0) Explode();
    }




    //private void Damage()
    //{
        //Collider[] enemies = Physics.OverlapSphere(transform.position, damage, whatIsEnemies);
        //for (int i = 0; i < enemies.Length; i++)
        //{
            //enemies[i].GetComponent<ShootingAi>().TakeDamage(explosionDamage);

            //if (enemies[i].GetComponent<Rigidbody>())
                //enemies[i].GetComponent<Rigidbody>().enemy.Health -= Damage;
        //}

        //Invoke("Delay", 0.05f);
    //}

    private void Explode()
    {
        if(explosion != null) Instantiate(explosion, transform.position, Quaternion.identity);


        Collider[] enemies = Physics.OverlapSphere(transform.position, explosionRange, whatIsEnemies);
        for (int i = 0; i < enemies.Length; i++)
        {
            //enemies[i].GetComponent<ShootingAi>().TakeDamage(explosionDamage);

            if (enemies[i].GetComponent<Rigidbody>())
                enemies[i].GetComponent<Rigidbody>().AddExplosionForce(explosionForce, transform.position, explosionRange);
        }

        Invoke("Delay", 0.05f);


    }
    private void Delay()
    {
        Destroy(gameObject);
    }
        

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.CompareTag("Bullet")) return;

        collisions++;

        if(collision.collider.CompareTag("Enemy") && explodeOnTouch) Explode();
    }

    private void Setup()
    {
        physics_mat = new PhysicMaterial();
        physics_mat.bounciness = bounciness;
        physics_mat.frictionCombine = PhysicMaterialCombine.Minimum;
        physics_mat.bounceCombine = PhysicMaterialCombine.Maximum;
        GetComponent<SphereCollider>().material = physics_mat;

        rb.useGravity = useGravity;
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, explosionRange);
    }

}

I can’t read all the code at this time but let me offer a guess that your bullet is colliding with your gun (or you). You can’t consider that a collision for most purposes.

It isn’t, I made sure it can’t.

First script, lines 70 and 76 should be ‘if (dead == true…’

1 Like

And you suppose that will fix the error?
Edit: It didn’t, but good spotting thanks, I fixed that up.

You should easily be able to debug what is triggering your kill floor, and work backwards from there. You don’t need us to debug this for you.

That is the thing, I can’t find what it is. So I am asking how I can make an extra check to make sure nothing else can.

Yes you can. You just need to Debug.Log what other is in OnTriggerEnter and work backwards from there.

I would love to set up another extra measure to make sure nothing like this happens again, do you have any idea? I understand what you are talking about and I will look through all that, but I do think having a bonus check would be good.

Don’t start trying to solve the problem until you have figured out the cause of the problem. Otherwise you’re just wasting your time. That’s the point of debugging. You haven’t finished debugging until you find what causes the bug.

Did some debugging, it seems to be a Enemy tagged object, did some looking but I am still unsure how to debug check for specific gameobjects that trigger the collision.

Did you read the scripting docs? Unity - Scripting API: Debug.Log

Namely it points out you can pass in a second parameter, which will ping the object passed through when the debug log is selected in the console.

Print the name of the game object that is passing your tag check, and pass it through as context.

I cannot believe I missed that part, I reread the doc about 6 times lol.
Now I know what the issue is being caused by, it is the enemies I have. But a large issue is now present, they shouldn’t be able to collide across the map like that. All of my code has nothing that should allow that as the model is far from my player.