Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Random color Help

Discussion in 'Scripting' started by Fekzh21, Feb 10, 2019.

  1. Fekzh21

    Fekzh21

    Joined:
    Dec 29, 2018
    Posts:
    18
    How could I modify this script so that the random color is applied to several 3D objects, since with this script I only manage to give it a random color one by one and it is of many colors, I want to put a random color to several 3d objects, not I know if he explains me well. Any advice help, thank you..
     
    Last edited: Feb 10, 2019
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    4,412
    Instead of using GetComponent<MeshRenderer>() you can use GetComponentsInChildren<MeshRenderer>() and you will get an array of mesh renderers, all the ones at or below the current GameObject this script is on.

    Code (csharp):
    1. MeshRenderer[] allMeshRenderers = GetComponentsInChildren<MeshRenderer>();
    Then you can iterate that array. It is not guaranteed to be in any particular order.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    4,412
    @Fekzh21 , I am responding to your private mail (let's keep it out here in public so everybody can benefit and learn and chip in).

    You need to use a for() loop to iterate the MeshRenders, not just operate on a single one as your original code does, something like:

    Code (csharp):
    1. for (int i = 0; i < allMeshRenderers.Length; i++)
    2. {
    3.   // do whatever you want with each one here, such as:
    4.   allMeshRenderers[i].material.color = ... your original code here
    5. }
     
    eses likes this.