Rémi Choquette
Rémi Choquette

Reputation: 45

Change sprite color in unity using GUI button

I'm creating a Unity program where I want to use a GUI button to change the color of a sprite. I have the following code in my script but I'm not sure how to change the color.

public GameObject WantedSprite;

private void DrawWindow(int windowID)
{
    if (GUI.Button(new Rect(50, 150, 100, 50), "Change the Ball's color"))
        {
            var component = WantedSprite.GetComponent<Color>();
            component.g = Random.Range(0, 255);
            component.r = Random.Range(0, 255);
            component.b = Random.Range(0, 255);
        }

I'm learning Unity so that's a little of my background, thank you!

Upvotes: 2

Views: 2303

Answers (1)

Bejasc
Bejasc

Reputation: 960

You're on the right track..

The component you want to reference is the SpriteRenderer on the game object. This has access to, and controls the color property.

Make a new instance of Color and assign it's values (note: you may need to set .a (alpha) property as well to 255, if the sprite goes transparent).

Once you've constructed the color, you can then assign the SpriteRenderers color to the new one.

   SpriteRenderer component = WantedSprite.GetComponent<SpriteRenderer>();

   Color newColor;

   newColor.r = Random.Range(0.00f,1.00f);
   newColor.g = Random.Range(0.00f,1.00f);
   newColor.b = Random.Range(0.00f,1.00f);
   newColor.a = 1;

   component.color = newColor;

Upvotes: 1

Related Questions