Make an object spawn one by one

Hi folks,

I am not very good at programming but wonder if yous can help me.

I am trying to make x amount of objects spawn one after the other after 1.5 seconds in a random position or set position (using emptys And tells the user out of how many targets they clicked on and missed.

What I have is:

for (int i = 0; i < spawnPoints.Length; i++){
	     Instantiate((Random.Range(0,2) == 0 ? PrefabA : PrefabB), spawnPoints*.position, Quaternion.identity);*
  • }*
    }
    AND
    if (Input.GetMouseButtonDown (0)) {

  •  		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);*
    
  •  		RaycastHit hit;*
    
  •  		// Casts the ray and get the first game object hit*
    
  •  		Physics.Raycast (ray, out hit);*
    
  •  		if (hit.collider.tag == "target") {* 
    
  •  			AddPoints (pointsPerTarget);*
    
  •  			Destroy (hit.collider.gameObject);*
    
  •  		}*
    
  •  		Physics.Raycast (ray, out hit);*
    
  •  		if (hit.collider.tag == "background") {*
    
  •  			AddMiss (pointsPerMiss);*
    
  •  		}*
    
  •  		Physics.Raycast (ray, out hit);*
    
  •  		if (hit.collider.tag == "civilian") {*
    
  •  			Application.LoadLevel ("S1ActionReport");*
    
  •  		}*
    
  •  	}*
    
  •  }*
    

Why do you cast the ray 3 times?

To do what you want to do, you could use Coroutines (1, 2)

Or you could do something like this

float timer = 0f;
float timeBetweenSpawns = 1.5f;
int i = 0;

void Update()
{
    timer += Time.deltaTime;
    if (timer >= timeBetweenSpawns && i < spawnPoints.Length)
    {
        SpawnObjects();
    }    
}

void SpawnObjects ()
{ 
    timer = 0f;
    Instantiate((Random.Range(0,2) == 0 ? PrefabA : PrefabB), spawnPoints*.position, Quaternion.identity);*

i++;
}