Help having NPC run from enemy

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);
}

}

}

}

First, use Code tags when posting code.

One problem with your code is that you’re calling both RunAway() and Move() every frame. It seems like you should call only one or the other, or you could get weird conflicting behavior. When if the player is near the enemy? Then your bear will simultaneously run away from the enemy and towards the player, which would make them mostly stand still.

See if your RunAway code works if you stop calling Move(), just to isolate things and keep it simpler.

The other issue is I bet “enemy” is null most of the time, unless you’re setting it in some other code. The way your code works here, the bear will find at most one enemy when Start() is called. If a different enemy approaches, nothing in your code tried to find new enemies. One way to fix this would be to start a Coroutine that checks for nearby enemies every second or so.