Hi, this is my first question in Unity Answers.
Recently a pair of good users helped me in giving me the base code for a script to spawn gameObjects in a list of places, and those places are transforms of other gameObjects i put in my scene, so the script spawn a deffined object (in the case of my game, a page the player needs to collect later) in one of the places i setup in the array via inspector…and the place is selected randomly by the script.
It just works fine, but…only one problem, the thing is that the script sometimes decides to use the same place again to spawn the new object, this causes sometimes the spawning of a seconf, third object and beyond…in the same place…, and this unfortunately doesn’t look good for anyone.
Then i was researching a bit, to know ways of preventing this: build a script to check and remove the duplicates if these are were spawned in the same place? and leave only 1 at that place? and respawn or move the deleted duplicates to some of the other places?(maybe too difficult and the same result)
So i thought about making my script to delete the entries of the array with the places transforms as it uses them, in other words:
Spawn an object in one of the listed places/transforms , and then, delete temporarily just the place that was used…so in the next spawn, the script won’t use that place again…
So, that’s it!, i only need this and the script would be perfect
I’ll leave you the code in Javascript:
import System.Collections.Generic;
var numberOfItems: int;
var newLevel: boolean;
static var loadedLevelName : String;
private var i : int;
var possibleSpawnPositions: Transform[];
var objectTypeToSpawn: GameObject;
function SpawnNewObject()
{
var spawnPointReference: Transform = GetSpawnPointReference();
var newObject: Transform = Instantiate(objectTypeToSpawn,
spawnPointReference.position, spawnPointReference.rotation) as Transform;
}
function GetSpawnPointReference():Transform
{
var randomIndex: int = Random.Range(0, possibleSpawnPositions.Length);
return possibleSpawnPositions[randomIndex];
}
function Start ()
{
if(newLevel)
{
switch(Application.loadedLevelName)
{
case "Mundo Alternativo":
numberOfItems = 8;
break;
default:
Debug.Log("Something is wrong here");
break;
}
for(i=0; i < numberOfItems; i++)
{
SpawnNewObject();
}
newLevel = false;
}
}
function Update ()
{
}
Thanks in advance!