Spawning objects on trigger does not work as expected

Hello everyone! I created an enemy spawning system, that does not work as it should. Here are the scripts.

Spawner

 #pragma strict
      
    function OnTriggerEnter(collision : Collider) {
    
    if(collision.CompareTag("Player"))
        {
    		print("YAY");
    		EnemySpawn.SpawnEnemy = true;
        }
    }

EnemySpawn

#pragma strict
var prefab : Rigidbody;
static var SpawnEnemy = false;

function Update () {
 if(SpawnEnemy == true){
  print("Enemy has spawned");
  Instantiate(prefab,transform.position,transform.rotation);
  SpawnEnemy = false;
  }
}

Those scripts should spawn 3 cubes(enemys) in 3 Empty GameObject positions (EnemySpawn1, EnemySpawn2, EnemySpawn3) with “EnemySpawn” script attached when a player enters a trigger. But the “EnemySpawn” script only spawns 1 cube(enemy) in 1 Empty GameObject position (EnemySpawn1) what did I do wrong? Thank you for help.

Hello, there! First of all, I suggest that instead of using boolean signals to tell SpawnEnemy to spawn, that you instead go a little more directly:
###EnemySpawn.js:

#pragma strict
var prefab : Rigidbody;
public function SpawnEnemy()//Create a public function we can call later
{
	print("Enemy has spawned");
	Instantiate(prefab,transform.position,transform.rotation);
}

###Spawner.js

public var eSpawn : EnemySpawn;
#pragma strict

function OnTriggerEnter(collision : Collider)
{
	if(collision.CompareTag("Player"))
	{
	   print("YAY");
	   eSpawn.SpawnEnemy();//Call the function we defined earlier
	}
}

But besides all of that, to actually answer your question, it seems that it only spawns one, because you only ever tell it to! Does your prefab contain more than one object in it? If not, I suggest doing this:

###EnemySpawn.js

#pragma strict
var prefab : Rigidbody;
public function SpawnEnemy()
{
	for (int i = 0; i < 3; i++)//Create a for loop that repeats its self 3 times
	{
		print("Enemy has spawned");
		Instantiate(prefab,transform.position,transform.rotation);
	}
}

I believe the issue is that your EnemySpawn1 instantiates an enemy, and then sets the static variable “SpawnEnemy” to false. Since it is a static variable, and that variable is now false, the other EnemySpawners will not spawn any enemies.

Try this:

Spawner

#pragma strict
function OnTriggerEnter(collision : Collider)
{
	if(collision.CompareTag("Player"))
	{
		print("YAY");
		var enemySpawners : GameObject[] = GameObject.FindGameObjectsWithTag("EnemySpawner");
		for(var enemySpawn : GameObject in enemySpawners)
		{
			enemySpawn.BroadcastMessage("SpawnEnemy");
		}
	}
}

EnemySpawn

#pragma strict
var enemyPrefab : GameObject;

function SpawnEnemy()
{
	print("Enemy has spawned");
	Instantiate(enemyPrefab, transform.position, transform.rotation);
}

Make sure to your EnemySpawners are tagged as “EnemySpawner”.