Search Unity

setting child colors

Discussion in 'Scripting' started by liewald, Sep 4, 2015.

  1. liewald

    liewald

    Joined:
    Apr 22, 2013
    Posts:
    6
    I have a model pf a brain that I have constructed from a number of submeshes that I would to iterate through and set colors according to some rules that I have developed.

    can anyone tell me the best way to iterate through such a structure and set the colors?

     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Code (CSharp):
    1. for (Transform child in transform) {
    2.    //set colors
    3. }
    Put this code into your parent object. This will go trough every child of the parent.
     
  3. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. class MonoBrain : MonoBehaviour
    7. {
    8.     public GameObject pial;
    9.  
    10.     private Dictionary<string, Material> nameToMaterial;
    11.     private void Start()
    12.     {
    13.         // Find all MeshRenderers nested under Pial
    14.         // Assuming they only exist on "default" GameObject below "rh.pial.DK.*"
    15.         MeshRenderer[] renderers = pial.GetComponentsInChildren<MeshRenderer>();
    16.  
    17.         nameToMaterial = new Dictionary<string, Material>();
    18.  
    19.         for (int i = 0; i < renderers.Length; i++)
    20.         {
    21.             // Find the name of the parent GO of the renderer.
    22.             string partName = renderers[i].transform.parent.name;
    23.  
    24.             // Creates a clone of the material.
    25.             Material partMaterial = renderers[i].material;
    26.  
    27.             // Add name and material to dictionary.
    28.             nameToMaterial.Add(partName, partMaterial);
    29.         }
    30.  
    31.         nameToMaterial["rh.pial.DK.fusiform"].color = Color.red;
    32.         nameToMaterial["rh.pial.DK.bankssts"].color = Color.blue;
    33.     }  
    34. }
    35.  
     
  4. liewald

    liewald

    Joined:
    Apr 22, 2013
    Posts:
    6
    Thanks guy's : Thermalfusion : thats pretty much what my final code looks like :D thanks
     
    ThermalFusion likes this.