- Home /
What is the best way to instantiate inside parent objects?
I'm building a spawn generator for items and enemies alike, and have already set up the defined zones with invisible cube gameobjects, using the colliders as triggers to define areas. However, now I'm trying to iterate through each box and place things within it at random. What would be the best way to do this? I'm already collecting the information for each area.
void populateArea(GameObject obj)
{
string areaType = obj.tag;
float areaX = obj.collider.bounds.size.x;
float areaY = obj.collider.bounds.size.y;
float posX = obj.transform.localPosition.x;
float posY = obj.transform.localPosition.y;
Rect area = new Rect(posX, posY, areaX, areaY);
Debug.Log (area);
switch(areaType)
{
case "Sides":
placeGrass(posX, posX);
break;
}
}
Answer by flaviusxvii · Feb 16, 2013 at 08:41 PM
Something like this.. (untested, I didn't run this, it's just scribbles..)
Transform newObject = Instantiate(grassOrWhatever, Vector3.zero, Quaternion.identity) as Transform;
newObject.parent = obj.transform;
newObject.localPosition = new Vector3(Random.Range(-areaX, areaX), 0, Random.Range(-areaY, areaY);
Answer by FL · Feb 16, 2013 at 08:45 PM
Call instantiateRandomObject()
, put the objects and percentage of each one. The chance of each will be percentage/percentageSUM.
var objectPercentage : ObjectPercentage[];
class ObjectPercentage{
var object : GameObject;
var percentage: int=0;
}
function instantiateRandomObject(){
var percentageTotal: int[] = new int[objectPercentage.length];
for(var count : int=0;count<percentageTotal.length;count++){
percentageTotal[count] = objectPercentage[count].percentage;
if(count!=0){
percentageTotal[count] += percentageTotal[count-1];
}
}
var randomNumber: int = Random.Range(1, percentageTotal[percentageTotal.length-1]);
var result : int = -1;
for(var i : int=0;i<percentageTotal.length;i++){
if(randomNumber<=percentageTotal[i]){
result = i;
break;
}
}
Object.Instantiate(objectPercentage[result].object,transform.position,transform.rotation);
}
Your answer
Follow this Question
Related Questions
Invisable Projectile; Instantiate at Collisions 2 Answers
Iterate through area descibed by objects 1 Answer
Checking if object intersects? 1 Answer
Instantiating inside an area only. 2 Answers