Search Unity

Game Object [ ]

Discussion in 'Scripting' started by mrgolemm, Dec 13, 2019.

  1. mrgolemm

    mrgolemm

    Joined:
    Jun 25, 2019
    Posts:
    16
    I have a script that changes the character color randomly to one of those specified in color. How can I make the color change only for Game Objects in the "body"


    Code (CSharp):
    1.  
    2.     private Renderer rend ;
    3.     public Color [] color;
    4.     public GameObject [] body;
    5.  
    6.     private void Start()
    7.     {
    8.      
    9.         {
    10.             rend = GetComponent<Renderer>();
    11.             rend.material.color = color [Random.Range(0, color.Length)];
    12.         }                                                  
    13.     }
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,639
    What does that mean?
     
  3. olejuer

    olejuer

    Joined:
    Dec 1, 2014
    Posts:
    211
    You are currently modifying the color of the material. I assume, all your renderer use that material instance. If they are supposed to use different colors, you will want to use property blocks and set them per renderer.
    You could also use a different material for the renderers that should be recolored and those that should not. However, this could end up in having many materials and this will be bad for performance, because it increases the number of draw calls. If you don't know what that means, nevermind.
    Your clue is property blocks :)

    Something like this (pseudo code, as I am on mobile. Might not compile. Also _Color might not be the right property name)
    Code (CSharp):
    1. var propertyBlock = new MaterialPropertyBlock();
    2. foreach(GameObject go in body) {
    3.     foreach(Renderer r in body.GetComponentsInChildren<Renderer>(){
    4.     r.GetPropertyBlock(propertyBlock);
    5.     propertyBlock.SetProperty("_Color", color);
    6.     r.SetPropertyBlock(propertyBlock);
    7. }
    8. }