Just wanted to see if my version of the script is OK

I decided to use the same thing from Fighter since we’re already doing the same thing with it, right? It seems to work fine but just wanted to see if anyone has any thoughts. I also cached the GO in Start since I read that trying to get other game objects is better in Start than Awake


namespace RPGTutorial.Control
{
    public class AIController : MonoBehaviour
    {
        [SerializeField] float chaseDistance = 5f;
        GameObject player;

        private void Start()
        {
            player = GameObject.FindWithTag("Player");
        }

        private void Update()
        {
            if(player == null) { return; }

            if (GetIsInRange())
            {
                print(gameObject.name + ":" + " Must. Give. Chase.");
            }
        }
        private bool GetIsInRange()
        {
            return Vector3.Distance(transform.position, player.transform.position) <= chaseDistance;
        }
    }
}

This code should work.

In this case, it’s ok to cache the Player in Start(), but there are situations where it’s imperative that you cache an external reference in Awake() to avoid a race condition with the Saving System (future lecture). It’s generally safe to cache the reference in Awake() but it’s seldom safe to actually access the reference in Awake().

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms