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

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 );

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);
    }
}

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

==