Search Unity

How to modify code to change material on all inactive child objects?

Discussion in 'Scripting' started by Proto-G, May 9, 2021.

  1. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    213
    I'm designing a character customizer and using this script to change the material on my characters. Currently it's only changing the material on the currently active character model. I would like to modify the code to also change the material on all inactive character models. Is this possible? Thanks!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. public class PlayerMaterialSwapper : MonoBehaviour {
    6.    
    7.      public Material mat;
    8.    
    9.      public void ChangeMaterial(Material mat)
    10.      {
    11.          SkinnedMeshRenderer[] children;
    12.          children = GetComponentsInChildren<SkinnedMeshRenderer>();
    13.          foreach (SkinnedMeshRenderer rend in children)
    14.          {
    15.              var mats = new Material[rend.materials.Length];
    16.              for (var j = 0; j < rend.materials.Length; j++)
    17.              {
    18.                  mats[j] = mat;
    19.              }
    20.              rend.materials = mats;
    21.          }
    22.      }
    23. }
     
  2. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    213
    Never mind. Figured it out. Just needed to add 'true' here:
    Code (CSharp):
    1. children = GetComponentsInChildren<SkinnedMeshRenderer>(true);