How to change a button image with script?
So I'm making a Level Select System, which should switch the image of a button once it's unlocked. I use a sprite as texture, but "button.image" does only work with "Image" and not with "Texture2D" or "Texture that I would have to use. Edit: I've also noticed, that tmptext = button.GetComponentInChildren<TMP_Text>();
and string gameObjectName = button.name;
don't work. I would appreciate help. using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using TMPro; using UnityEngine.UI;
public class SwitchToLevel : MonoBehaviour
{
public bool locked;
public int Level;
public int LevelCount;
int accessibleLevels;
public Image lockedTexture;
public Image unlockedTexture;
public Button button;
TMP_Text tmptext;
void Start()
{
accessibleLevels = UnlockNextLevel.instance.getLockState();
string gameObjectName = button.name;
float requestedLevel = float.Parse(gameObjectName);
if (requestedLevel <= accessibleLevels)
{
locked = false;
}
}
void Update()
{
if (locked == false)
{
tmptext = button.GetComponentInChildren<TMP_Text>();
tmptext.enabled = false;
button.image = unlockedTexture;
}
else
{
button.image = lockedTexture;
}
}
public void LevelToGo()
{
if (locked == false)
{
// hier ist ne Zeile die den Typ zum Level sendet
// some german, ignore this
}
else
{
}
}
}
Answer by joemane22 · Mar 08, 2020 at 08:07 PM
In unity a Texture2D is the resource of the texture in memory and is applied to either a material or a sprite but is not used by it self to be displayed on the screen. You need to assign the texture to the Sprite of the image the button uses. So instead of having two images declared have two textures that represent the locked and unlocked state.
Then when it is locked or unlocked you set the buttons image.sprite accordingly.
Seeing that a sprites texture property is a get only property you need to have the sprites premade and set the sprite instead.
So declare two sprites you can create in the start function
Sprite unlockedSprite;
Sprite lockedSprite;
public Texture2D unlockedTexture;
public Texture2D lockedTexture;
public Image stateImage;
void Start()
{
unlockedSprite = Sprite.Create(unlockedTexture, new Rect(0, 0, unlockedTexture.width, unlockedTexture.height), new Vector2(0.5f, 0.5f));
lockedSprite = Sprite.Create(lockedTexture, new Rect(0, 0, lockedTexture.width, lockedTexture.height), new Vector2(0.5f, 0.5f));
}
Then when locked or unlocked you can set the sprite accordingly like this stateImage.sprite = unlockedSprite;
Your existing code is close, just change what I described and drop in the appropriate textures in the inspector and you should be good to go.
I wrote this on my phone so forgive me for any errors!
Your answer
Follow this Question
Related Questions
UI button class 1 Answer
UI buttons won't recognize script 0 Answers
Button Displacement 0 Answers