- Home /
Fast layer assignment
Hi, I need to add a gameobject and all its children to a layer via c# code. In editor i'm asked if i want to add the single object or the whole hierarchy. i wonder if there is an equally fast way to do this in a script without writing explicit code
Answer by skovacs1 · Sep 02, 2010 at 07:21 PM
To put a stop to your wondering, the short answer is that there is no implemented method to do this that I can find.
As == says, you will have to recurse through the hierarchy.
You could do something like:
//recursive calls
void MoveToLayer(Transform root, int layer) {
root.gameObject.layer = layer;
foreach(Transform child in root)
MoveToLayer(child, layer);
}
or
//no recursive calls
using System.Collections;
void MoveToLayer(Transform root, int layer) {
Stack<Transform> moveTargets = new Stack<Transform>();
moveTargets.push(root);
Transform currentTarget;
while(moveTargets.Count != 0)
{
currentTarget = moveTargets.Pop();
currentTarget.gameObject.layer = layer;
foreach(Transform child in currentTarget)
moveTargets.Push(child);
}
}
Answer by Bezzy · Aug 07, 2013 at 11:39 AM
An extension version of the above for anyone who wants:
using UnityEngine;
using System.Collections;
public static class TransformExtensions
{
public static void SetLayer(this Transform trans, int layer)
{
trans.gameObject.layer = layer;
foreach(Transform child in trans)
child.SetLayer( layer);
}
}
Use like this:
someOtherGameObject.transform.SetLayer( gameObject.layer );
Would upvote, but too new to the forums! Thanks for this.
Answer by equalsequals · Sep 02, 2010 at 02:16 PM
There is no reason you couldn't recursively move down the top-most object's transform hierarchy and set each gameobject's layer accordingly.
Add this script to your Editor folder:
using UnityEngine; using UnityEditor; using System.Collections;
public class LayerChanger : ScriptableWizard {
public int layer;
public GameObject gameObject;
[MenuItem ("GameObject/Manage Layers Recursively")]
static void CreateWizard () {
ScriptableWizard.DisplayWizard("Manage Layers", typeof (LayerChanger),"Improv!");
}
void OnWizardCreate () {
Pew(gameObject);
}
void Pew(GameObject g)
{
g.layer = layer;
foreach(Transform t in g.transform)
{
t.gameObject.layer = layer;
Pew(t.gameObject);
}
}
}
Cheers
==
I know. I was asking if there is already a method to do this
Did the question specify whether the code being asked about was for the editor or the run-time? I figured since the editor will do this for you as the question describes that they didn't really need an editor script. Thanks for covering the other interpretation - one of us has to have the correct answer.