Layer Controller

Posted: 18 Oct 2023 12:26
by Elringus

In camera-rendered layered actors following component can be used to handle layer events in batch for all children renderer components (to not set them individually):

Code: Select all

using System.Collections.Generic;
using UnityEngine;

public class LayerController : MonoBehaviour
{
    private readonly List<Renderer> renderers = new List<Renderer>();

    private void Awake () => GetComponentsInChildren<Renderer>(true, renderers);

    public void HandleLayerHeld (int layer)
    {
        foreach (var renderer in renderers)
            SetLayer(renderer, true, layer);
    }

    public void HandleLayerReleased (int layer)
    {
        foreach (var renderer in renderers)
            SetLayer(renderer, false, layer);
    }

    private void SetLayer (Renderer renderer, bool enabled, int layer)
    {
        renderer.enabled = enabled;
        renderer.gameObject.layer = layer;
    }
}

Attach the component to the layer's root object and hook the handlers to Layered Actor Layer as follows:

Image