I have the following code to create objects at random locations (I still need to write the random code):
public GameObject objectPrefab;
void Start()
{
StartCoroutine( SpawnObjects() );
}
IEnumerator SpawnObjects()
{
while( true )
{
Instantiate( objectPrefab, /*however you need to determine a valid random position*/, Quaternion.identity );
yield return new WaitForSeconds( 1.0f );
}
}
Now to initiate it I apparently need to put the code in a class and attach it to an empty object (Thanks Tetrad for that!). But I was wondering how I could go about creating and using this class in the context of this problem?
using UnityEngine;
using System.Collections;
public class SameNameAsFilename : MonoBehaviour
{
public GameObject objectPrefab;
void Start()
{
StartCoroutine( SpawnObjects() );
}
IEnumerator SpawnObjects()
{
while( true )
{
Instantiate( objectPrefab, /*however you need to determine a valid random position*/, Quaternion.identity );
yield return new WaitForSeconds( 1.0f );
}
}
}
If it's the same name as the filename and is a monobehaviour, you'll be able to just drag it onto a gameobject in the scene
The two using statements are to make the unity and IEnumerator specific parts compile
The only problem I'm having is it isn't creating one object per second like it should. Thousands of objects fly out until it crashes. I can only assume its because it keeps calling the script over and over again. I can't figure out what the problem is :/.
Heres the completed code:
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour
{
private Vector3 tempVector;
public GameObject objectPrefab;
void Start()
{
StartCoroutine( SpawnObjects() );
}
IEnumerator SpawnObjects()
{
tempVector = new Vector3(0.5f, 0.5f, 0.5f);
while( true )
{
Instantiate( objectPrefab, tempVector, Quaternion.identity);
yield return new WaitForSeconds( 1.0f );
}
}
}