C#C
C#4y ago
cccc

Bullet Kills Wrong Enemy

If I shoot and hit an enemy, sometimes it will kill the wrong one.
For example, if i hit 'EnemyTest', it might end up killing 'EnemyTest (2)' that is miles away.

BulletController Code:
using UnityEngine;

public class BulletController : MonoBehaviour
{
    public float shootSpeed;
    float freezeTime = .15f; 
    Rigidbody m_Rigidbody;
    float bulletFreeze = 2f;
    private GameObject reelBack;
    public GunController gunScript;
    Enemy1 enemyScript;

    // Start is called before the first frame update
    void Start()
    {
        gunScript = GameObject.FindObjectOfType<GunController>();
        enemyScript = GameObject.FindObjectOfType<Enemy1>();
        reelBack = GameObject.FindGameObjectWithTag("POINT");
        m_Rigidbody = GetComponent<Rigidbody>();
        gunScript.canFire = false;
    }

    // Update is called once per frame
    void Update()
    {
        freezeTime -= Time.deltaTime;   //new
        if (freezeTime <= 0)
        {
            m_Rigidbody.constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationZ;
            bulletFreeze -= Time.deltaTime;
            if (bulletFreeze <= 0)
            {
                Destroy(gameObject, .2f);
                transform.LookAt(reelBack.transform);
                m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
                transform.position += transform.forward * 100*Time.deltaTime;
                gunScript.canFire = true;
            }
        }
        if (freezeTime > 0)
        {
            transform.Translate(Vector3.up * shootSpeed * Time.deltaTime);
            
        }

        //transform.Translate(Vector3.up * shootSpeed * Time.deltaTime);
        //Destroy(gameObject, 3);

    }
    ***private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy")
        {
            Debug.Log("HIT");
            enemyScript.takeDamage(5);
            

        }***
    }
}
Was this page helpful?