I have 3 enemy spawners. Once the camera is on one of the spawners that specific spawner needs to be deactivated. I tried this by creating a bool called “canSpawn”.
yet, the detected spawner will still spawn an enemy called “bochel”.
i tried using chatGPT to fix this but it didn’t help. I’m quite new to unity and programming so i’m really struggling here! So i’d like some help ![]()
Here is the code:
using System.Collections;
using UnityEngine;
public class enemySpawningScript : MonoBehaviour
{
public GameObject bochel;
public GameObject cameraObject; // Assuming this is your camera object
private int randomSpawningNumber = 0;
private int coolDown = 20;
private int maxCoolDown = 20;
private bool canSpawn = true;
void Start()
{
canSpawn = true;
StartCoroutine(SpawnEnemy());
}
private IEnumerator SpawnEnemy()
{
while (canSpawn) //the spawning sequence will run while this bool is true
{
randomSpawningNumber = Random.Range(1, 10);
coolDown = Random.Range(8, maxCoolDown);
Debug.Log("rsn =" + randomSpawningNumber + " cd =" + coolDown);
yield return new WaitForSeconds(coolDown);
if (randomSpawningNumber > 8)
{
InstantiateEnemy();
}
if (Input.GetKeyDown(KeyCode.B))
{
randomSpawningNumber = 9;
}
}
}
// Update is called once per frame
void Update()
{
}
public void InstantiateEnemy()
{
// Instantiate the bochel GameObject at the spawner's position
Instantiate(bochel, transform.position, transform.rotation);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject == cameraObject)
{
canSpawn = false; //disable the spawner as soon as the camera trigger detects this
Debug.Log("Camera entered spawner trigger.");
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject == cameraObject)
{
canSpawn = true; //enable the spawner again as soon as the camera trigger no longer detects this
Debug.Log("Camera exited spawner trigger.");
}
}
}