- Home /
My script only makes two clones.
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);
}
}
}
Answer by RahulRaman · Feb 03, 2020 at 01:19 AM
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;
}
}
}
Thanks for the help! And I didn't need that variable actually. That came from another script and I forgot to delete it :/
Answer by LeFlop2001 · Feb 02, 2020 at 10:28 PM
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
Answer by kevinyan010 · Feb 03, 2020 at 12:36 AM
how can I make it spawn one box every 2 seconds?
@kevinyan010 You should add comments to answers ins$$anonymous$$d of adding answer to question for asking things.
Use the function InvokeRepeating(„functionName“,InvokeDely,TimeBetweenCalls).
public float spawnTime;
public GameObject boxPrefap;
void Start()
{
InvokeRepeating(„SpawnBox“,0,spawnTime);
}
void SpawnBox()
{
Instantiate(boxPrefab,position,rotation)
}