Question by
Nannooskeeska · Feb 18, 2016 at 03:09 AM ·
scripting problemfollowfollow playerfollowing
FollowObject script not working on spawned enemies
I have a FollowObject script, shown here:
public Transform Player;
public float MoveSpeed = 4;
public float MaxDist = 10;
public float MinDist = 5;
void Update ()
{
transform.LookAt (Player);
if (Vector3.Distance (transform.position, Player.position) >= MinDist) {
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance (transform.position, Player.position) <= MaxDist) {
//Here Call any function U want Like Shoot at here or something
}
}
}
It works fine when I have an enemy prefab in the game world when I start. However, when I spawn an enemy (or multiple enemies) with this script:
public GameObject prefabToSpawn;
public float spawnTime;
public float spawnTimeRandom;
private float spawnTimer;
// Use this for initialization
void Start ()
{
ResetSpawnTimer ();
}
// Update is called once per frame
void Update ()
{
spawnTimer -= Time.deltaTime;
if (spawnTimer <= 0.0f) {
Instantiate (prefabToSpawn, transform.position, Quaternion.identity);
ResetSpawnTimer ();
}
}
void ResetSpawnTimer ()
{
spawnTimer = (float)(spawnTime + Random.Range (0, spawnTimeRandom * 100) / 100.0);
}
They do not follow the player; instead, they move towards the place where the player originally started.
Any ideas? I'm not entirely sure what the problem would be here.
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612064646im_/https://answers.unity.com/themes/thub/images/avi.jpg)