- Home /
Replacing empty gameobjects with prefabs
I have a prefab with some empty gameobjects as anchor points for other prefabs. I want to replace there empty gameobject with a random prefab from an array, keeping the position, rotation and scale.
This way I hope to achieve 'randomly' generated blocks.
Answer by Antony-Blackett · Mar 28, 2011 at 09:15 PM
You can do this with a script by going:
public GameObject[] prefabs; // assign these in the editor.
void GenerateRandomBlocks() {
foreach(Transform child in transform) { int randomIndex = Random.Range(0,prefabs.length - 1); GameObject randomBlock = Instantiate(prefabs[randomIndex], child.transform.position, child.transform.rotation); // this creates a new prefab of a random type at the transform of the child object. randomBlock.transform.localScale = child.transform.localScale; // this applies the child's scale to the new object. randomBlock.parent = transform; // this assigns the new object as a child of the child's parent. } }
Then place this script on the object that contains all the locators for random blocks
I'd really like to use this script, but the "prefabs.length" as well as the "randomblock.parent" show up as undefined in monodevelop, is there something in the script that I need but didn't have already?
Answer by toddisarockstar · Jan 31, 2016 at 10:18 PM
var all:GameObject[];
all=GameObject.FindObjectsOfType(GameObject);//get objects in scene
var i :int;
var fab0:GameObject;//<--drag n drop you block prefabs here in the inspector
var fab1:GameObject;
var fab2:GameObject;
var fabs:GameObject[];
fabs=new GameObject[3];
fabs[0]=fab0;
fabs[1]=fab1;
fabs[2]=fab2;
for (var obj:GameObject in all){
//put your spawn point objects in the scene with the name "marker"!!!
if(obj.transform.name.Contains("marker"){
i=Random.Range(0,3);
Instantiate(fabs[i],obj.transform.position, fabs[i].transform.rotation);}
}
Answer by Mekiah · Feb 05, 2016 at 02:49 AM
try makeing the prefab a child object of the empty gameobject