簡體   English   中英

Unity3D C# 按鈕精靈交換 - 在運行時附加圖像

[英]Unity3D C# Button sprite swap - attach images at runtime

我正在創建“英雄選擇菜單”時創建按鈕 這些按鈕將根據它們所代表的“英雄”獲得相關的圖像/精靈

我有以下方法,但我不明白我必須將精靈應用到哪個變量

Button _thisButton;
Sprite  _normalSprite;
Sprite _highlightSprite;

protected override void DoStateTransition (SelectionState state, bool instant){
    switch (state) {
    case Selectable.SelectionState.Normal:
        _thisButton.image = _normalSprite;    //.image is not correct
        Debug.Log("statenormalasd");
        break;
    case Selectable.SelectionState.Highlighted:
        _thisButton.image = _normalSprite;    //.image is not correct
//...
    }

這些狀態肯定有效,我已經通過 Debug.Log(...) 確認了它;

同樣的問題是:如果不是.image,則必須更改哪個值?

提前致謝, Csharpest

您正在嘗試將精靈附加到按鈕組件。 精靈位於Image組件中。 看一下這個!

GameObject buttonGameObject;
Sprite newSprite;

void Start() {
    buttonGameObject.GetComponent<Image>().sprite = newSprite;   
}

但是為了修復你的代碼,你可能會做類似的事情:

Button _thisButton;
Sprite  _normalSprite;
Sprite _highlightSprite;

protected override void DoStateTransition (SelectionState state, bool instant){
    switch (state) {
    case Selectable.SelectionState.Normal:
        _thisButton.GetComponent<Image>().sprite = _normalSprite;   
        Debug.Log("statenormalasd");
        break;
    case Selectable.SelectionState.Highlighted:
        _thisButton.GetComponent<Image>().sprite = _normalSprite;    
    }

如果你想在腳本中更改按鈕spriteswap sprite,你必須使用spriteState ,你可以這樣做;

Button _thisButton;
Sprite  _normalSprite;
Sprite _highlightSprite;

void ChangeSprites(){
  // _thisButton.transition = Selectable.Transition.SpriteSwap;
  var ss = _thisButton.spriteState;
  _thisButton.image.sprite = _normalSprite;
  //ss.disabledSprite = _disabledSprite;
  ss.highlightedSprite = _highlightSprite;
  //ss.pressedSprite = _pressedSprie;
  _thisButton.spriteState = ss;
}

如果您使用普通按鈕並選擇SpriteSwap,Unity會自動交換按鈕,如果您需要更改轉換選項,則取消注釋該函數的第一行。

您可以通過在運行時更改圖像組件的 sprite 屬性來實現。

button1.GetComponent<Image>().sprite = sprite;

完整的演示代碼:

using UnityEngine;
using UnityEngine.UI;

public class SpriteChangeDemo : MonoBehaviour
{
    public Button button1;
    public Sprite sprite1, sprite2;

    void Start()
    {
        ChangeSprite(sprite1);
        ChangeSprite(sprite2);
    }

    public void ChangeSprite(Sprite sprite) {
        button1.GetComponent<Image>().sprite = sprite;  
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM