// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Microsoft.MixedReality.Toolkit.UI { /// /// This is required since UnityUI Graphic elements do not support MaterialPropertyBlocks, and any shader operations can end up modifying the material permanently across all shared instances. /// To prevent that we create a runtime copy of the material. /// public class UIMaterialInstantiator { // this set ensures that we do not end up creating multiple copies of materials for every theme targeting the same instance private static HashSet targetInstances = new HashSet(); /// /// Invoke this method to create a copy of the material and use that copy at runtime for Graphic objects to prevent modifying materials in editor or impact shared materials. /// /// Graphic element that needs to clone its material public static void TryCreateMaterialCopy(Graphic targetGraphic) { int targetId = targetGraphic.GetInstanceID(); if (!targetInstances.Contains(targetId)) { targetInstances.Add(targetId); targetGraphic.material = new Material(targetGraphic.material); } } } }