I'll show you how to infinitely (and semi-randomly) spawn sprites vertically! First off we'll declare some of the things we need. I use orbs in my game, but you should feel free to change anything at all
private GameObject lastOrb; private Vector2 pos; //Define the rage in which each object is allowed to spawn public float fromY; public float toY; public float fromX; public float toX; public GameObject orbPrefab; //If you want more than one gameObject to spawn declare them aswell and set them in the editor. public GameObject pinkOrbPrefab; public GameObject redOrbPrefab; public GameObject blueOrbPrefab;
Now we need to set the first sample point for the script to work.
void SampleGenerate()
{
if(lastOrb == null)
{
// Here i have a single orb preplaced as a starting point for the script.
// The name of the object is what you put in GameObject.Find(), it should be unique.
lastOrb = GameObject.Find("OrbFirst");
}
}
With a first point of reference we're going to start out
void SampleGenerate()
{
if(lastOrb == null)
{
lastOrb = GameObject.Find("OrbFirst");
}
pos = lastOrb.transform.position;
pos.y += Random.Range(fromY,toY);
pos.x += Random.Range(fromX,toX);
InstOrb();
}
//Here you just select a random range of numbers depending on how many items you have.
//I want my standard orbPrefab to be spawned much more often then my other orbs so it has a 7 in 10 chance.
void InstOrb()
{
int Select = Random.Range(0,10);
switch(Select)
{
case 0:
lastOrb = Instantiate(orbPrefab,pos,Quaternion.identity) as GameObject;
break;
case 1:
lastOrb = Instantiate(pinkOrbPrefab,pos,Quaternion.identity) as GameObject;
break;
case 2:
lastOrb = Instantiate(blueOrbPrefab,pos,Quaternion.identity) as GameObject;
break;
case 3:
lastOrb = Instantiate(redOrbPrefab,pos,Quaternion.identity) as GameObject;
break;
default:
lastOrb = Instantiate(orbPrefab,pos,Quaternion.identity) as GameObject;
break;
}
}
Now all we have left to do is utilize the script in our Update function. I don't recommend just keeping it in the Update function as it will slow your game down dramatically. I recommend setting a cycle for it to run once.
Cycle:
void Start()
{
//Amount of objects to spawn/cycles to run
int cycles = 10;
for(int i = 0; i < cycles; i++)
{
SampleGenerate();
}
}
OR [!SLOW WARNING!] Infinite:
void Update()
{
SampleGenerate();
}