Search Unity

switch color just for one of instances

Discussion in 'Scripting' started by dot-syntax, Apr 6, 2010.

  1. dot-syntax

    dot-syntax

    Joined:
    Apr 16, 2009
    Posts:
    30
    Hey, so I've got that quick question, hopefully you could help me out.

    I wanted to create coins on a button press,
    that will switch colors interchangeably.
    So that one would be yellow, the other one - red, the next one - yellow, etc.
    but with that code
    Code (csharp):
    1.  
    2. var coin: Transform;
    3. var Red = true;
    4.  
    5. if(Input.GetButtonDown("Jump")){
    6.         Instantiate(coin, transform.position, Quaternion.identity);
    7.         if(Red){
    8.         coin.renderer.material.color = Color.red;
    9.          Red = false;
    10.         }
    11.         else if(!Red){
    12.         coin.renderer.material.color = Color.yellow;
    13.         Red = true;
    14.         }
    15.     }
    it seems that when I press Jump
    ALL of the coins in the scene change color at once.
    They all become red,
    or yellow, on the next press.

    How could I fix it so it behaves as intended?
    Thank you in advance.

    -Dot
     
  2. matthewminer

    matthewminer

    Joined:
    Aug 29, 2005
    Posts:
    331
    Rather than changing the original prefab's colour, which is what your script is doing, you need to store the newly created coin in a variable and change its colour.

    Code (csharp):
    1. var coin : Transform;
    2. var red = true;
    3.  
    4. if (Input.GetButtonDown("Jump")) {
    5.     var clone : Transform;
    6.     clone = Instantiate(coin, transform.position, Quaternion.identity);
    7.    
    8.     if (red) {
    9.         clone.renderer.material.color = Color.red;
    10.     } else {
    11.         clone.renderer.material.color = Color.yellow;
    12.     }
    13.    
    14.     red = !red;
    15. }