Small Fix C#

Hi guys! :slight_smile: I Have a Script here. This script is to be placed to my RPG AI. But I don’t understand
why the AI Just Instantly Follow when i press Play. Any Ideas :)?

SCRIPT:

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour
{
    public Transform target;
    public int minRange;
    public bool  follow;
    public float speed;
    public int moveSpeed;
    public int rotationSpeed;
    private Transform myTransform;
    public GameObject enemy;
    	
    void Awake()
    {
        myTransform = transform;
    }
    
    void Update ()
    {
        GameObject go = GameObject.FindGameObjectWithTag("Player");
        if(Vector3.Distance(go.transform.position, go.transform.position) < minRange)
            target = go.transform;
        
        EnemyHealth eh = (EnemyHealth)enemy.GetComponent("EnemyHealth");
        eh.ttarget = target;
        follow=true;
        
        if(follow)
        {
            myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
            transform.LookAt(target);
            myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
        }
    }
}

LINK HERE ( it was may to long :confused: )

if(Vector3.Distance(go.transform.position,go.transform.position)<minRange)

You’re checking the distance between something and ITSELF for starters. That’s the first thing that jumped out at me.

Edit :
You also don’t have this stuff in brackets for the “if”->

target = go.transform;

EnemyHealth eh = (EnemyHealth)enemy.GetComponent("EnemyHealth");

eh.ttarget = target;
follow=true;

Which means if your gameobject distance between it and itself is less than minRange, then target = that object … and everything else after that before your next “if” will happen every update, so either way follow will always be true.

I guess you want something like that:

public class EnemyAI : MonoBehaviour
{
    public int minRange;
    public bool follow;
    public float moveSpeed;
    public float rotationSpeed;
    private Transform myTransform;
    private Transform player;

    void Start()
    {
        myTransform = transform;
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    void Update ()
    {
        if(Vector3.Distance(player.position, myTransform.position) < minRange)
        {
            EnemyHealth eh = enemy.GetComponent<EnemyHealth>();
            eh.ttarget = player; // are you sure ".ttarget" is named correctly?
            follow=true;
        }
        
        if(follow)
        {
            myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(player.position - myTransform.position), rotationSpeed * Time.deltaTime);
            myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
        }
    }
}