- Home /
How to Organize Hierarchy at run time?
I'm procedurally generating content but it shows up in the hierarchy root at run time. Is there any way to change parent/child relationships in the hierarchy at run time to organize the game objects.
Example. I'm creating a 2D scrolling level at run time by creating X game objects, assigning sprites to them, and rendering them one after the other. I have an empty game object acting as an organizational element called "Level" with children "Foreground", "Playarea", and "Background". I want my generated content to show in it's appropriate relative parent/child relationship within the hierarchy.
Does anyone know how I can accomplish this programmatically?
Answer by kalen_08 · Aug 06, 2017 at 10:11 PM
yes of course!! just go:
private GameObject parent;
public void CreatIfNeeded (string objectName)
{
parent = GameObject.Find (objectName);
if (!parent)
{
parent = new GameObject(objectName);
}
}
private void Fire ()
{
GameObject newGameGeneration = Instantiate (projectile) as GameObject;
newGameGeneration .transform.parent = parent.transform;
newGameGeneration .transform.position = //Whatever the position is that your spawning it at;
}
so basically what this is going to do is check if there is a game object by the name of objectName. if there isn't, it will create one called parent. All created content, when instantiated, could be put as a child to it like how I have it in the script above.
sorry about some of that, I took it from my own scripts so ignore the "projectiles" and "Fire" as names for the function and what it would be spawning.
Your answer
Follow this Question
Related Questions
File organization help? 2 Answers
Is it better to check before you change variable 2 Answers
organize unity inspector with collapsable sections without using classes 1 Answer
How to efficiently copy a mesh modified during runtime? 1 Answer
How to use NavMeshSurface and NavMeshModifier to build navmesh with obstacles at runtime? 1 Answer