Advertisement
Guest User

ChangeMaterialChildrenCleaned

a guest
May 31st, 2017
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using UnityEngine;
  4.  
  5. //This attribute is used so the component is working in also Edit Mode  (not in play)
  6. [ExecuteInEditMode]
  7. public class ChangeMaterialChildren2 : MonoBehaviour
  8. {
  9.     //Class to simplify the visualization on inspector window
  10.     [System.Serializable]
  11.     private class MeshMaterial
  12.     {
  13.         public MeshRenderer targetMeshRenderer;        //Target meshRender to apply targetMaterial
  14.         private Material targetMaterial;                //Target maaterial to apply to meshRenderer
  15.     }
  16.  
  17.     public Material masterMaterial;
  18.  
  19.     [SerializeField]
  20.     private List<MeshMaterial> meshMaterial;  //List of combination of MeshRenderer - Targetmaterial
  21.  
  22.     [SerializeField]
  23.     private bool updateAll = false;           //Used on inspector to update all meshRenderer in the list meshMaterial
  24.  
  25.     private void Update()
  26.     {
  27.         //When you check the box (uptadeAll)
  28.         if (updateAll)
  29.         {
  30.             //apply all the materials
  31.             foreach (var m in meshMaterial)
  32.                 m.targetMeshRenderer.sharedMaterial = masterMaterial;       //changed to update from masterMaterial
  33.  
  34.             //Reset updateAll, otherwise this is called every frame (not ideal)
  35.             updateAll = false;
  36.         }
  37.     }
  38.  
  39.     //This is called when you attach this component on a gameObject, so I use it to initialize
  40.     private void Reset()
  41.     {
  42.         meshMaterial = new List<MeshMaterial>();
  43.  
  44.         //I assume that your "carpets" are 3D models, so i'll search all children items of this gameobject with MeshRenderer component.
  45.         List<MeshRenderer> mr = GetComponentsInChildren<MeshRenderer>().ToList();
  46.  
  47.         //If i recall correctly GetComponentsInChildren will include the parent (this gameobject) so i remove the parent
  48.         MeshRenderer myMeshRenderer = GetComponent<MeshRenderer>();
  49.         if (myMeshRenderer != null)
  50.             mr.Remove(myMeshRenderer);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement