OK the problem I’m having is with my spawner being difficult in the way I’m trying to program the destruction of it. The way I have it programmed is that I have my player tagged and when it walks through a trigger enemies spawn at the child object location. The enemies move towards the player until it reaches a certain distance and stop spawning. This is all done by disabling and enabling the Spawner Script.
However, the enemies still respawn and don’t move when I reach the max distance. I tried destroying the parent object thus destorying the child with it when I reach a certain distance, but when I have multiple spawn areas in the scene and the player not even close they all get destroyed. I get no warnings or errors, so I know all my references are set up correctly.
Some reason disabling the Spawner Script in the StopSpawning method is not working and I know that the method is being called. Here are my three scripts that are dealing with my current spawn system.
public class EnemyAI : MonoBehaviour {
private GameObject player;
public float distance;
public float range = 30f;
private GameObject enemySpawnTrigger;
void Awake (){
player = GameObject.FindGameObjectWithTag("Player");
enemySpawnTrigger = GameObject.FindGameObjectWithTag("EnemySpawnTrigger");
}
void FollowTarget(){
distance = Vector2.Distance (transform.position, player.transform.position);
if (distance <= range){
transform.position = Vector2.MoveTowards(
transform.position, player.transform.position,
moveSpeed * Time.deltaTime);
}
else if (enemySpawnTrigger != null && distance > range)
enemySpawnTrigger.GetComponent<SpawnTrigger>().StopSpawning();
}
void Update () {
FollowTarget ();
}
}
public class SpawnTrigger : MonoBehaviour {
public Spawner spawner; // Reference to the PlayerControl script.
void Awake (){
spawner = GetComponentInChildren<Spawner>();
GetComponentInChildren<Spawner>().enabled = false;
}
void Start () {
spawner = GetComponentInChildren<Spawner>();
}
void OnTriggerEnter2D(Collider2D player){
if (player.tag == "Player"){
GetComponentInChildren<Spawner>().enabled = true;
}
}
public void StopSpawning(){
//Destroy (gameObject);
GetComponentInChildren<Spawner>().enabled = false;
Debug.Log ("this method is being called");
}
}
public class Spawner : MonoBehaviour{
public float spawnTime = 5f;
public float spawnDelay = 3f;
public GameObject[] enemies;
void Start (){
InvokeRepeating("Spawn", spawnDelay, spawnTime);
}
void Spawn (){
int enemyIndex = Random.Range(0, enemies.Length);
Instantiate(enemies[enemyIndex], transform.position, transform.rotation);
}
}