在做某事时永远改变ImageButton的图像

时间:2016-06-22 11:26:09

标签: c# image unity3d imagebutton

如上所述,我想在做某事时(点击或几秒钟后)更改ImageButton的图像。

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

当我点击按钮时,它看起来效果很好,但当鼠标移出按钮时,更改的图像被重新更改为第一张图像。

我使用Debug.Log函数测试了spriteName,我检查了sprite是否自动重新更改。

如果永久发生某些事件,如何更改ImageButton的图像?

1 个答案:

答案 0 :(得分:1)

对于新项目,您应该使用uGUI,这是Unity的新UI系统。

您可以使用Button.onClick.AddListener(() => callbackFunction())注册到按钮事件,然后可以使用Button.image.sprite = newSprite;更改按钮图像中的精灵。您需要在脚本顶部加入using UnityEngine.UI;

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();
}