简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM