GroupOpacityController.cs (using Update)
using UnityEngine; [ExecuteAlways] public class GroupOpacityController : MonoBehaviour { [Range(0f, 1f)] public float opacity = 1f; Renderer[] renderers; SpriteRenderer[] spriteRenderers; float _previousOpacity; void Start() { renderers = GetComponentsInChildren<Renderer>(); spriteRenderers = GetComponentsInChildren<SpriteRenderer>(); SetOpacity(opacity); } void Update() { if(opacity != _previousOpacity) { SetOpacity(opacity); _previousOpacity = opacity; } } void SetOpacity(float opacity) { if (renderers != null) { foreach (Renderer renderer in renderers) { for (int i = 0; i < renderer.sharedMaterials.Length; i++) { Color color= renderer.sharedMaterials[i].color; color.a = opacity; MaterialPropertyBlock matBlock = new MaterialPropertyBlock(); matBlock.SetColor("_Color", color); renderer.SetPropertyBlock(matBlock, i); } } } if (spriteRenderers != null) { foreach (SpriteRenderer spriteRenderer in spriteRenderers) { Color color = spriteRenderer.color; color.a = opacity; spriteRenderer.color = color; } } } }
GroupOpacityController.cs (using Property)
using UnityEngine; [ExecuteAlways] public class GroupOpacityController : MonoBehaviour { [SerializeField, Range(0f, 1f)] float _opacity = 1f; public float Opacity { get { return _opacity; } set { _opacity = Mathf.Clamp01(value); SetOpacity(_opacity); } } Renderer[] renderers; SpriteRenderer[] spriteRenderers; #if UNITY_EDITOR void OnValidate() { SetOpacity(_opacity); } #endif void Start() { renderers = GetComponentsInChildren<Renderer>(); spriteRenderers = GetComponentsInChildren<SpriteRenderer>(); SetOpacity(_opacity); } void SetOpacity(float opacity) { if (renderers != null) { foreach (Renderer renderer in renderers) { for (int i = 0; i < renderer.sharedMaterials.Length; i++) { Color color= renderer.sharedMaterials[i].color; color.a = opacity; MaterialPropertyBlock matBlock = new MaterialPropertyBlock(); matBlock.SetColor("_Color", color); renderer.SetPropertyBlock(matBlock, i); } } } if (spriteRenderers != null) { foreach (SpriteRenderer spriteRenderer in spriteRenderers) { Color color = spriteRenderer.color; color.a = opacity; spriteRenderer.color = color; } } } }