- Home /
Enemy only chasing pre-fab's original location, not instance's
I have an enemy (called Monster3) whose behavior is controlled by the below script:
using UnityEngine;
using System.Collections;
public class Monster3AI : MonoBehaviour {
public Transform player;
private float pursueSpeed = 3;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
transform.position=Vector3.MoveTowards(transform.position,player.position,pursueSpeed*Time.deltaTime);
}
}
In the Inspector, I dragged the Player prefab onto the area under Monster3AI where it asks for the reference, and it says, "Player (Transform)". I believe this should result in Monster3 chasing after the instance of the Player, but instead, it's chasing after the transform.position of the prefab of the Player. Of course the prefab itself never moves, so all instances of Monster3 just go to the same location.
How can I can tell it to go after the instance of Player and not the prefab?
Answer by robertbu · May 07, 2014 at 12:13 AM
I assuming that the Player is Instantiated() and therefore does not exist in the Scene? If the player exists in the scene, in Edit mode, then you've somehow dragged the wrong 'Player' on the variable. If the player is Instantiated(), then make sure it is created before the Monster3AI game object, then you can do this in Start():
player = GameObject.Find("Playder (clone)").transform;
Or better yet, tag your player with a "Player" tag then you can do:
player = GameObject.FindWithTag("Player");
None if you initialize 'player' this way, then it it can be private or protected instead of public.
Answer by Datsusara · May 07, 2014 at 04:33 AM
Thank you! Yes, to answer your question, Player is Instantiated() and does not exist in the scene. I did a combination of your two answers:
player = GameObject.FindWithTag("Player").transform;
I'm not sure if it was a typo, but in the second one, you left off the .transform, so it didn't work the first time I tried it. Then I figured out my mistake, and now it works!