[Lecture Enemy Spawning and flow]
Hi all, good day. I am trying to tweak around with different spawning conditions and none of the condition i coded works lol…
As you can see from the image, i have Spawners gameobject with 5 spawner child in it.
My goal:
If lizard has been spawned on the lane 3, do not spawn it on lane 3.
My idea: create a bool (isAllowedToBeSpawned) to " getchild by name to find if Lizard exist as spawner’s child" , if yes return true. And if it is true, do not spawn.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawner : MonoBehaviour {
public GameObject[] attackerPrefabArray;
public float spawnerChild;
public GameObject lz;
// Use this for initialization
// Update is called once per frame
void Update () {
foreach (GameObject thisAttacker in attackerPrefabArray){
if (isTimeToSpawn (thisAttacker)) {
// lizard is under 1 of the attackerPrefabArray (fox is 0)
// if this attacker is lizard, and there is a no lizard child in this spawner, spawn it
if((thisAttacker == attackerPrefabArray.GetValue(1)) && isAllowedToBeSpawned())
Spawn (thisAttacker);
}
}
print (transform.childCount);
}
bool isTimeToSpawn(GameObject attackerGameObject){
Attacker attacker = attackerGameObject.GetComponent<Attacker>();
float meanDelayTime = attacker.seenEverySeconds;
float spawnsPerSecond = 1 / meanDelayTime;
if (Time.deltaTime > meanDelayTime) {
Debug.LogWarning ("spawnrate capped at frame rate");
}
float threshold = spawnsPerSecond * Time.deltaTime / 5 ; //is to normalise
if (Random.value < threshold) {
return true;
} else {
return false;
}
}
bool isAllowedToBeSpawned(){
//to find if there is any lizard child in this spawner object
lz = this.transform.Find("lizard").gameObject;
if (lz != null) {
return false;
} else {
return true;
}
}
void Spawn(GameObject myGameObject){
GameObject myAttacker = Instantiate (myGameObject) as GameObject;
myAttacker.transform.parent = transform;
myAttacker.transform.position = transform.position;
}
}
End result:
“NullReferenceException: Object reference not set to an instance of an object
spawner.isAllowedToBeSpawned () (at Assets/spawner.cs:54)”
spawner.Update () (at Assets/spawner.cs:20)".
Disclaimer: programming is never my forte =(
And… I am not sure what to put into this
bool isAllowedToBeSpawned(GameObject ???)
I’ve actually posted this question on Udemy. But that is like an extension of another question. Hence, i am posting it here… in a cleaner way. Thanks for the help in advance. Cheers!
