- Home /
Automatically parenting a gameobject when placed in the scene
Hi, is there a way to automatically parent an prefab when you place it into the scene? I am level building and its a pain to move every item from the root to the correct parent object.
I assume that its easily done in using a simple transform.parent in an editor script, but I dont know if there is some method that runs when the object is created, rather than everytime it is selected.
Is there some kind of method I can use when the object is placed in the scene?
Answer by Thomas-Hawk · Jan 26, 2017 at 03:04 AM
Do you mean, upon instantiation? Or when you drag it into the scene? To parent a gameobject when dragging it into a scene, drag it onto the name in the hierarchy or the object in the scene view. To parent a gameobject when instantiated by a script on runtime, Instantiate takes a parameter for that. https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Answer by NerdRageStudios · Jan 26, 2017 at 03:14 AM
Sorry, I meant on dragging into the scene. I can drag them manually, but my level structures are deep and complex, so thats not possible.
for now, this is the solution I have come up with, but if there is a better way, please let me know!
I just attach this script to the prefab: using UnityEngine; using System.Collections;
[ExecuteInEditMode]
public class EditorAutoPlacement : MonoBehaviour {
public string parentName;
[HideInInspector]
public bool alreadyPlaced = false;
void Awake()
{
if (Application.isEditor && !alreadyPlaced)
{
transform.parent = GameObject.Find(parentName).transform;
alreadyPlaced = true;
}
}
}