Different gameobjects don't use same script independently

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 :slight_smile:

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.");
        }
    }
}

1 Answer

1

Some questions/suggestions based on your code:

  1. If TriggerEnter is called while you’re in cooldown, then it will spawn one more time in any case, because your InstantiateEnemy method is after cooldown (maybe you should move spawning code before cooldown or check the flag inside while after cooldown and break the loop)
  2. On TriggerEnter you set your flag to false which may terminate your coroutine and I don’t see you start it again (if this happens right before cooldown end)
  3. Based on the previous point, I’d suggest to rewrite this using Update method and timer rather than coroutine