Search Unity

Question Auto Aim doesn't work properly

Discussion in 'Scripting' started by thom5225, Feb 12, 2024.

  1. thom5225

    thom5225

    Joined:
    Feb 12, 2024
    Posts:
    1
    Hi, i´m working on a 2d top down shooter, and i want to implement a auto aim feature, i was following a tutorial, but i have done it exactly as the person, the problem is that when the character changes the enemy looking at, the last one doesn´t recognize it as a enemy and it doesn´t aim at him, this is the code:

    weapon[] weaponView;
    public List<GameObject> enemiesList = new List<GameObject>();
    public GameObject closestEnemy;
    public float maxRange = 100f;

    private void Start()
    {
    weaponView = GetComponentsInChildren<weapon>();
    MovementEnemy[] enemiesInScene = FindObjectsOfType<MovementEnemy>();
    foreach (MovementEnemy enemy in enemiesInScene)
    {
    enemiesList.Add(enemy.gameObject);
    }
    }
    private void Update()
    {

    ClosestEnemy();
    if(closestEnemy != null)
    {
    enemiesList.Remove(closestEnemy);
    }
    }

    void ClosestEnemy()
    {
    float range = maxRange;
    foreach(GameObject enemyGameObject in enemiesList)
    {
    float dist = Vector3.Distance(enemyGameObject.transform.position,transform.position);
    if (dist < range)
    {
    range = dist;
    closestEnemy = enemyGameObject;
    }
    }
    foreach (weapon weapon in weaponView)
    {
    weapon.fireTarget = closestEnemy;
    }
    } [/code]