Uri M
Uri M

Reputation: 21

Trying to change color with a script in Unity - SpriteRenderer.color doesn't work

i'm a new to unity and trying to change a sprite's color through a script. i'm following this tutorial page: https://www.tutorialspoint.com/unity/unity_coroutines.htm. i'm using Unity 2019.2.0f1

when pressing "play" i can see the colors changing every second in the inspector, but nothing happens in the scene

the code:

public class colorChanger : MonoBehaviour {

public int                 seconds_interval;
public SpriteRenderer     sr;
public Color             color_1;
public Color             color_2;

IEnumerator changeColor(){

    while (true){

        if (sr.color == color_1){
            sr.color = color_2;
        } else {
            sr.color = color_1;
        }

        yield return new WaitForSeconds(seconds_interval);
    }

}

// Start is called before the first frame update
void Start()
{
    sr = gameObject.GetComponent<SpriteRenderer>();
    StartCoroutine( changeColor() );
    //sr.color = color_1;
}

// Update is called once per frame
void Update()
{

}

}

explanation and screenshots:

this is the sprite, notice it starts as purple, then the script should change it's color: https://i.ibb.co/rQy2Lpr/1.jpg

when pressing "play" i can see the colors changing every second in the inspector, but nothing happens in the scene: yellow: https://i.ibb.co/DRhcpPT/2.jpg

green (after 1 second): https://i.ibb.co/Yc0v26K/3.jpg

actually, the inspector is totaly ignored by the scene! notice that the sprite is white (and not purple/yellow/green). notice that if i change the scale nothing happens in the "play" screen: https://i.ibb.co/sjdCvfw/4.jpg

but when i go back to "game" screen (without stopping the game), the frame of the sprite changes but not it's actual size: https://i.ibb.co/R054Rv0/5.jpg

it looks like the script is making the inspector disconnect from the scene. is it a bug? or am i missing something here?

thank you :)

Upvotes: 0

Views: 2835

Answers (1)

Uri M
Uri M

Reputation: 21

solved!

my problem was that: I have chosen colors in the UI interface while their Alpha property was 0. so i couldn't see any color changing.

I still don't understand why the "scale" property wasn't reacting to live changes in the inspector, but choosing colors with Alpha of 255 (opacity) solved everything.

Upvotes: 0

Related Questions