Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- //This attribute is used so the component is working in also Edit Mode (not in play)
- [ExecuteInEditMode]
- public class ChangeMaterialChildren : MonoBehaviour
- {
- //Class to simplify the visualization on inspector window
- [System.Serializable]
- private class MeshMaterial
- {
- public MeshRenderer targetMeshRenderer; //Target meshRender to apply targetMaterial
- private Material targetMaterial; //Target maaterial to apply to meshRenderer
- /* Removing individual updating
- * public bool updateMaterial; //Used on inspector window to apply targetMaterial on meshRenderer
- */
- }
- public Material masterMaterial;
- [SerializeField]
- private List<MeshMaterial> meshMaterial; //List of combination of MeshRenderer - Targetmaterial
- [SerializeField]
- private bool updateAll = false; //Used on inspector to update all meshRenderer in the list meshMaterial
- private void Update()
- {
- //When you check the box (uptadeMaterial) in the inspector of an item in the meshMaterial list
- /* Removing individual updating
- MeshMaterial itemToUpdate = meshMaterial.Find(m => m.updateMaterial == true);
- if (itemToUpdate != null)
- {
- itemToUpdate.targetMeshRenderer.sharedMaterial = itemToUpdate.targetMaterial; //Applying material to meshRenderer
- //Setting to false again because we already applied to material
- //other wise this is called every frame (not ideal)
- itemToUpdate.updateMaterial = false;
- }
- */
- //When you check the box (uptadeAll)
- if (updateAll)
- {
- //apply all the materials
- foreach (var m in meshMaterial)
- m.targetMeshRenderer.sharedMaterial = masterMaterial; //changed to update from masterMaterial
- //Reset updateAll, otherwise this is called every frame (not ideal)
- updateAll = false;
- }
- }
- //This is called when you attach this component on a gameObject, so I use it to initialize
- private void Reset()
- {
- meshMaterial = new List<MeshMaterial>();
- //I assume that your "carpets" are 3D models, so i'll search all children items of this gameobject with MeshRenderer component.
- List<MeshRenderer> mr = GetComponentsInChildren<MeshRenderer>().ToList();
- //If i recall correctly GetComponentsInChildren will include the parent (this gameobject) so i remove the parent
- MeshRenderer myMeshRenderer = GetComponent<MeshRenderer>();
- if (myMeshRenderer != null)
- mr.Remove(myMeshRenderer);
- //Initializing the list of MeshRenderers affected
- /*
- foreach (var r in mr)
- {
- MeshMaterial meshMat = new MeshMaterial()
- {
- targetMeshRenderer = r,
- targetMaterial = r.sharedMaterial, //By default the targetMaterial is the current material of the mesh renderer
- /* Removing Individual updating
- * updateMaterial = false
- *
- };
- meshMaterial.Add(meshMat);
- }*/
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement