- Home /
How to set instantiated objects as children of another instantiated object?
Ok, so I'm trying to solve this :
objects have a boolean called "selected" right clicking on the objects toggles this on and off.
When I press 'B', I want an empty gameobject to be Instantiated and set as the parent of all selected objects. I can then select more objects, press 'B', creating another group, and so on.
I've been working on this for hours and getting nothing but headaches
Answer by supernat · Sep 15, 2013 at 11:31 PM
I assume you already have a method to keep track of the selected objects and you have a reference to the object that is to become the parent. To parent one object to another, use something like this:
GameObject childObj; // Set this to the child you want to give a home
GameObject parentObj; // Set this to the parent
childObj.transform.parent = parentObj.transform.parent;
hmm, actually, the references are where I'm having trouble.
There are several ways to handle this. Basically, you want to intercept the press of the letter B, so we'll do that in an Update() method somewhere. I like to create a "$$anonymous$$anager" game object that has a script on it that performs some important global task, like processing the input in this case, though you don't always want to do it this way. The key is, in your case, you only want to process B in one class's (game object's) instance, so create an empty game object in your scene and add an Update() method to process the key B.
The next step is to find out which objects are selected. I think this is a perfect case to use static members. If you have 5 cubes with a CubeScript on them, and in the CubeScript, you are handling the right mouse click, you could add something like the following to CubeScript:
// Set this prefab to a prefab of the same cube as the current object this script is attached to.
public GameObject cubePrefab;
public static List<GameObject> children;
void On$$anonymous$$ouseUp()
{
// Do whatever you are doing now to deter$$anonymous$$e this was right clicked
if (rightClicked)
{
if (children.Exists(gameObject))
children.Remove(gameObject);
else
children.Add(gameObject);
}
}
public static void CreateNewParent()
{
if (children.Count > 0)
{
GameObject obj = (GameObject)Instantiate(cubePrefab, new Vector3.zero, Quaternion.identity);
foreach (GameObject child in children)
{
child.transform.parent = obj.transform;
}
}
}
Now, just call CubeScript.CreateNewParent() from your $$anonymous$$anager class that is receiving the "B" keypress.
Thank you! that was exactly what I needed help with. thanks for showing me such a simplified way of doing it
Your answer
![](https://koobas.hobune.stream/wayback/20220613114233im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to create a login system online? 1 Answer
Basic Scripting help 2 Answers
character creation 2 Answers