김보근
김보근

Reputation: 11

Change an image of ImageButton permenantly when do something

As above, I want to change an image of ImageButton when do some event (clicked or few seconds later).

void OnclkMe(GameObject go)
{
    go.GetComponentInChildren<UISprite>().spriteName = "NumCard_01";
}

When I clicked the button, It looks like work well, but the changed image was re-changed to first image when a mousepoint move out of button.

I tested the spriteName using Debug.Log func, and I checked that sprite was re-changed automatically.

How can I change an image of ImageButton when occur some of event permanently ?

Upvotes: 0

Views: 103

Answers (1)

Programmer
Programmer

Reputation: 125455

For new projects, you should use uGUI which is Unity's new UI system.

You can register to button event with Button.onClick.AddListener(() => callbackFunction()) and you can change the sprite in the button's image with Button.image.sprite = newSprite;. You need to include using UnityEngine.UI; at the top of your script.

public Button button1;
public Button button2;

public Sprite newSprite;

void OnEnable()
{
    //Register Button Events
    button1.onClick.AddListener(() => buttonCallBack(button1));
    button2.onClick.AddListener(() => buttonCallBack(button2));
}

private void buttonCallBack(Button buttonPressed)
{
    if (buttonPressed == button1)
    {
        //Your code for button 1
        buttonPressed.image.sprite = newSprite;
    }

    if (buttonPressed == button2)
    {
        //Your code for button 2
    }
}

void OnDisable()
{
    //Un-Register Button Events
    button1.onClick.RemoveAllListeners();
    button2.onClick.RemoveAllListeners();
}

Upvotes: 1

Related Questions