I have a script that I tried to use to make my box make clones but it only makes two. This is my code: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy1script : MonoBehaviour
{
// Start is called before the first frame update
public Transform target;
public Rigidbody enemy;
public float force = 1.0f;
private float num_of_enemies;
void Start()
{
StartCoroutine(ACoroutine());
num_of_enemies = 1;
}
// Update is called once per frame
void Update()
{
if (num_of_enemies > 5) {
ACoroutine();
}
}
IEnumerator ACoroutine()
{
yield return new WaitForSeconds(2f);
spawnEnemy(1);
num_of_enemies += 1;
}
void spawnEnemy(int number)
{
for(int i = 0; i < number; i++)
{
Instantiate(enemy, new Vector3(Random.Range(-75,75), 5, Random.Range(-75, 75)), Quaternion.identity);
}
}
}
All the code you need to spawn one box every two seconds is following:-
using System.Collections;
using UnityEngine;
public class Enemy1script : MonoBehaviour
{
Transform target; // Why do you need this variable BTW
public Rigidbody enemy;
public float force = 1.0f;
// Initially set enemies to 0
private float num_of_enemies = 0;
void Start()
// Start the coroutine in start function
{ StartCoroutine(ACoroutine()); }
// No need of update function to spawn enemies regularly at 2 seconds
IEnumerator ACoroutine()
{
// Using while true here will loop the code block forever
while (true)
{
spawnEnemy(1);
// The line below will stop the loop for 2 seconds and then it again cycles
yield return new WaitForSeconds(2f);
}
}
void spawnEnemy(int number)
{
for (int i = 0; i < number; i++)
{
Instantiate(enemy, new Vector3(Random.Range(-75, 75), 5, Random.Range(-75, 75)), Quaternion.identity);
// increment enemies count per instance
num_of_enemies += 1;
}
}
}
In your spawn function you have a for loop. In that for loop you make use of the variable „number“. And that number is set in your numerator under the function call. Simply the increase the int from 1 to whatever
how can I make it spawn one box every 2 seconds?