Have an NPC that follows player when close enough remains stationary when the player goes a certain distance from them. Im trying to get the NPC to also move away from an enemy if they come within a certain distance, these enemies spawn randomly, cant figure out why this isnt working, amny help would be much apreciated im super new to all thi, here is my code.
public class BabyBear : MonoBehaviour
{
public float speed = 3;
public GameObject player;
public GameObject enemy;
int noOfEnemy;
int EB;
// Start is called before the first frame update
void Start()
{
player = GameObject.Find(“Player”);
enemy = GameObject.Find(“Enemy Bear”);
noOfEnemy = GameObject.FindGameObjectsWithTag(“Enemy”).Length;
}
// Update is called once per frame
void Update()
{
RunAway();
Move();
}
private void Move()
{
var distVal = 10.0f;
var dis = Vector3.Distance(transform.position, player.transform.position);
if (dis <= distVal)
{
transform.LookAt(player.transform);
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}
void RunAway()
{
if (enemy != null)
{
var distval1 = 10.0f;
var dis1 = Vector3.Distance(transform.position, enemy.transform.position);
if (dis1 <= distval1)
{
Vector3 moveDir = transform.position - enemy.transform.position;
transform.Translate(moveDir.normalized * speed * Time.deltaTime);
}
}
}
}