Change a button's image/sprite

Hi.

I have tried a bunch of things to try to change a button’s image to a JPG/PNG from a file in unity.

Can someone help with this?

I can get the object OK with:
myButton=GameObject.Find(“StartButton”);

But how do I read a JPG/PNG into a texture and then apply it to the button using script only?

Any help would be appreciated.

Thanks in advance.

Before we go any further, and I know you assert it is working, but always:

Remember the first rule of GameObject.Find():
Do not use GameObject.Find();

More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

Second, buttons don’t have textures on them. By default buttons are colocated with Image components, which actually have the texture on them as a Sprite.

That said, the canonical way to access any UI Image in code is to:

  1. make a public Image MyButtonImage; variable (and drag the Image reference in here)

  2. use that reference to set the new Sprite on the Image:

MyButtonImage.sprite = desiredSprite;

All of this is covered in pretty much any basic UI tutorial. You should really ramp up on that stuff or you’re going to waste a lot of time fumbling around in the dark with a complicated UI system.

1 Like

Thanks for this Kurt,

You are right about GameObject.Find - I definitely agree that its a poor choice of getting an object handle and I can definitely see the pitfalls of using it. I am still learning and this helps out.

The problem I’m dealing with is that the sprite needs to be created from a JPG/PNG file on the local drive (or potentially as a URL) and then loaded in, and then finally applied to the button. So dragging an image reference isn’t going to cut it.

Any help on that part would be very helpful.

1 Like

So that’s stages in a pipeline flow of data, from JPG to your image.

You can think of it as:

  • png file - problem: get it into memory (see google for this, either off disk or off the net or off the user’s device; each way is different, all are well-documented in tutorials.)

  • now you have a Texture2D after the above step, time to make a Sprite out of it (Sprite.Create()) is your friend.

And finally when you have this freshly-created sprite, you can now assign it to your button.

If you need to save the image locally, google for that, as it’s a separate set of issues.