Now it will only spawn to 10 powerups. when 1 is collected, it doesn't spawn to 10 powerups
[SerializeField] public GameObject[] spawnPowerups;
public int amountOfPowerUpsToSpawn = 10;
[SerializeField] public float PowerupsWaitTime = 1f;
IEnumerator SpawnPowerUpsCoroutine()
{
for (int i = amountOfPowerUpsToSpawn; i > 0; i--)
{
int spawnPointX = Random.Range(-18, -3);
int spawnPointY = Random.Range(5, 0);
Vector3 spawnPosition = new Vector3(spawnPointX, spawnPointY, 0);
Instantiate(spawnPowerups[Random.Range(0, spawnPowerups.Length)], spawnPosition, Quaternion.identity);
yield return new WaitForSeconds(PowerupsWaitTime);
}
}
void Start()
{
StartCoroutine(SpawnPowerUpsCoroutine());
}
CodePudding user response:
I think maybe this is what you want to achieve. I made some changes and replaced the for with a while loop. Also added something to test the powerup collection to trigger the spawner on pickup. Tis code below.
PowerUpSpawner.cs
[SerializeField] public GameObject[] spawnPowerups;
public int amountOfPowerUpsToSpawn = 10;
public int PowerupsWaitTime = 1;
private int currentPowerUps = 0;
private Coroutine _coroutine;
public void PickedUpPowerUp()
{
currentPowerUps--;
//Check if Coroutine is null
if(_coroutine is null)
{
_coroutine = StartCoroutine(SpawnPowerUpsCoroutine());
}
}
IEnumerator SpawnPowerUpsCoroutine()
{
while (currentPowerUps < amountOfPowerUpsToSpawn)
{
int spawnPointX = Random.Range(-5, 5);
int spawnPointY = Random.Range(5, 0);
Vector3 spawnPosition = new Vector3(spawnPointX, spawnPointY, 0);
GameObject clone = Instantiate(spawnPowerups[Random.Range(0, spawnPowerups.Length)], spawnPosition, Quaternion.identity);
//Set parent to get the spawner
clone.transform.SetParent(transform, false);
//Increment powerups counter
currentPowerUps ;
yield return new WaitForSeconds(PowerupsWaitTime);
}
//Set coroutine to null
_coroutine = null;
}
void Start()
{
_coroutine = StartCoroutine(SpawnPowerUpsCoroutine());
}
PowerUp.cs
private PowerUpSpawner powerUpSpawner;
private void Start()
{
powerUpSpawner = GetComponentInParent<PowerUpSpawner>();
}
private void onm ouseDown()
{
powerUpSpawner.PickedUpPowerUp();
Destroy(gameObject);
}
CodePudding user response:
Add this to the script you sent.
IEnumerator SpawnPowerup()
{
yield return new WaitForSeconds(PowerupsWaitTime);
int spawnPointX = Random.Range(-18, -3);
int spawnPointY = Random.Range(5, 0);
Vector3 spawnPosition = new Vector3(spawnPointX, spawnPointY, 0);
Instantiate(spawnPowerups[Random.Range(0, spawnPowerups.Length)], spawnPosition, Quaternion.identity);
}
and call this from your Collecting Powerup script
YourPowerupGameobject.GetComponent<YourComponent>().SpawnPowerup();