Experimental Spawning Rate base on separate timers

I also didn’t like Ben’s original solution, as someone had said it was more a chance to spawn every amount of seconds than spawn every passage of time. When I was coming with an alternative solution I came to a conclusion that each type of villain would need its separate timer that would reset after spawning an instance of him, but keep timer of other villains going. To seenEveryXSeconds I added a small random range value to prevent form too much of regularity in distances between assailants. I also randomized lanes on which they are being spawned like someone before me. I very much like the result, more so that it isn’t overly complicated, rather simple idea. I also want to thank others for posting here.
There are a couple of unnecessary Debug.Log I needed to add for myself. Enjoy :slight_smile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour {

	public GameObject[] attackerPrefabArray;
	public GameObject[] spawnerLines;
	private GameObject parent;
	private float elapsedTime = 0f;
	private float foxTimer = 0f;
	private float lizardTimer = 0f;

	void Start () {
		parent = GameObject.Find ("Attackers");
		if (!parent) {
			parent = new GameObject ("Attackers");

	void Update () {

		foxTimer += Time.deltaTime;

		lizardTimer += Time.deltaTime;

		foreach (GameObject thisAttacker in attackerPrefabArray) {
			Debug.Log (thisAttacker);
			Debug.Log (elapsedTime);
			if (isTimeToSpawn (thisAttacker)) {
				Spawn (thisAttacker);
				if (thisAttacker.GetComponent<Lizard> ()) {
					lizardTimer = 0f;
				} else if (thisAttacker.GetComponent<Fox> ()) {
					foxTimer = 0f;

	bool isTimeToSpawn (GameObject attackerGameObject) {
		Attacker attacker = attackerGameObject.GetComponent<Attacker> ();
		Debug.Log ("Checking for bool");
		if (attackerGameObject.GetComponent<Fox>()) {
			Debug.Log ("Fox component found");
			elapsedTime = foxTimer;
		} else if (attackerGameObject.GetComponent<Lizard> ()) {
			Debug.Log ("Lizard component found");
			elapsedTime = lizardTimer;

		if (elapsedTime > attacker.seenEverySeconds + Random.Range(0f,2f)) {
			return true;
			return false;
	void Spawn (GameObject myGameObject) {
		GameObject myAttacker = Instantiate (myGameObject) as GameObject;
		int i = Random.Range (0,5);
		myAttacker.transform.parent = spawnerLines [i].transform;
		myAttacker.transform.position = spawnerLines[i].transform.position;


Privacy & Terms