I created an enemy object name “bat” and wrote a script that make “bat” can follow player.This game object working well. But when i turn that enemy object as a prefab, this prefab can’t follow player as game object did. Unity show this error: “UnassignedReferenceException: The variable hero of bat_controller has not been assigned. You probably need to assigned the hero variable of the bat_controller script in the inspector”.
Here is my code:
public Transform hero;
public float force;
private Rigidbody2D rb;
private Vector3 movedir;
private Vector3 batscale;
public float speed;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start () {
batscale = transform.localScale;
}
void Update () {
movedir = (hero.position - transform.position).normalized;
transform.Translate(movedir * Time.deltaTime * speed);
if (hero.position.x < transform.position.x)
{
transform.localScale = new Vector3(batscale.x, batscale.y);
}
else if(hero.position.x > transform.position.x)
{
transform.localScale = new Vector3(-batscale.x, batscale.y);
}
}