- Home /
Create Special Plane Objects at runtime
I am attempting to create 5 Special Plane objects on the fly at runtime.
My Problem: The objects(SpecialPlane) are created but they are never shown or added to the 'Hierarchy'. I have an empty game object called TerrainManager, it has a C# script added to it that is supposed to create 5 SpecialPlane objects/MonoBehaviour objects then add them to the hierarchy. It successfully creates the 5 planes AFAIK but it doesn't add them to the hierarchy, why?
How can I successfully create 5 SpecialPlane objects (dynamically at runtime) and add them to the hierarchy?
using System;
using System.Collections;
using System.Collections.Generic;
public class TerrainManager : MonoBehaviour {
static readonly uint DEF_PLANE_NUM = 5;
List <SpecialPlane> planes;
void Start () {
// Create n planes: this code compiles and runs but the planes are never shown?
for (int i=0; i<DEF_PLANE_NUM; i++) {
SpecialPlane plane = gameObject.AddComponent<SpecialPlane>();
planes.Add (planes);
}
// read file that contains a list of url's that lead to a .png which is a texture
// for each plane: get them to download their mesh from the url obtained from the text file
// setPlaneMesh("www.url.com/mesh/1.png");
}
}
public class SpecialPlane : MonoBehaviour {
void Start () {
MeshRenderer r = gameObject.AddComponent<MeshRenderer>();
MeshFilter f = gameObject.AddComponent<MeshFilter>();
}
void setPlaneMesh(string urlMesh) {
StartCoroutine( downloadMesh(urlMesh) );
}
}
Answer by whydoidoit · Jul 13, 2012 at 07:18 AM
You code would not add them to the hierarchy, but add them as scripts on the gameObject that has TerrainManager attached to it - was that your intention? If you want them as individual objects then you would need to create a GameObject inside the initialization loop - you also appear to have a typo where you add them to the List - I'm surprised this compiles...
const int DEF_PLANE_NUM = 5; //Should be consistent between int and loop counter
List <SpecialPlane> planes;
void Start () {
// Create n planes: this code compiles and runs but the planes are never shown?
for (var i=0; i<DEF_PLANE_NUM; i++) {
var go = new GameObject("SpecialPlane");
var plane = go.AddComponent<SpecialPlane>();
planes.Add (plane); //You had planes here in your example
}
}
...