#Short code review!

1 messages · Page 1 of 1 (latest)

bold nebula
#

I actually don't know how to use threads yet

lethal yacht
#
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");

this is a BIG no-no . . .

bold nebula
#

so I heard, but I can't think of any other way to work around it

#

I also realized how stupidly repetitive my code is like right now and got rid of one method

#
public class EnemyController : MonoBehaviour
    {
        [SerializeField] float attackRange = 5f;

        private void Update()
        {
            GameObject[] players = GameObject.FindGameObjectsWithTag("Player");

            float currentPlayer = GetClosestPlayer(players);

            if (currentPlayer < attackRange)
            {
                print("Can attack");
            }
        }

        private float GetClosestPlayer(GameObject[] players)
        {
            Transform nearestPlayer = null;
            float minDist = Mathf.Infinity;
            foreach (GameObject player in players)
            {
                float distance = Vector3.Distance(player.transform.position, transform.position);
                if (distance < minDist)
                {
                    nearestPlayer = player.transform;
                    minDist = distance;
                }
            }
            return minDist;
        }
    }
lethal yacht
#

you don't need to grab all players every frame. when a player is created, add them to a list. when they are destroyed, remove them from the list, then use the list to check the players . . .

mystic anchor
#

Generally, if performance is a concern, you should use the profiler.

bold nebula
lethal yacht