按鈕在 Unity Canvas 中被選中時無法突出顯示。我只想要 mausehover/pointerEnter 東西。
我正在制作基于平臺的 2D 手機游戲。用戶無需離開螢屏即可移動手指。所以我不需要 Pressed 和 Selected 狀態。
在PointerEnter 狀態下按鈕的alpha 最大,在PointerExit 狀態下按鈕的alpha 為100/255。而已。
嘗試過將 Transition 更改為 Sprite Swap 之類的方法;比如在 Unity 中嘗試 Toggle 組件而不是 Button。但是我被卡住了,我不知道解決方案是什么。
uj5u.com熱心網友回復:
您根本無法使用該Button組件,而是擁有一個簡單的組件并“自己完成”-正如您所說的使用IPonterEnterHandler / IPointerExitHandler界面
public class HoverButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
[SerializeField] private Image image;
[SerializeField] private Color normal = new Color(1f, 1f, 1f, 0.4f);
[SerializeField] private Color hover = Color.white;
// event called when pointer enters this button
public UnityEvent onEnter;
// event called once a frame while the button stays hovered
public UnityEvent whileHovered;
// event called when pointer exits this button
public UnityEvent onExit;
// wasn't sure if you still want fade effects
// if not you can of course skip all related stuff and just hard assign the image.color
[SerializeField][Min(0f)] private float fadeDuration = 0.2f;
private Coroutine currentRoutine;
private float currentFactor;
private void Awake()
{
if(!image) image = GetComponent<Image>();
}
private IEnumerator Fade(bool isHover)
{
var targetColor = isHover ? hover : normal;
var targetFactor = isHover ? 1f : 0f;
if(fadeDuration > 0f)
{
var step = (isHover ? (1 - currentFactor) : currentFactor) / fadeDuration;
while(!Mathf.Approximately(currentFactor, targetFactor))
{
currentFactor = Mathf.MoveTowards(currentFactor, targetFactor, step * Time.deltaTime);
image.color = Color.Lerp(normal, hover, currentFactor);
whileHovered.Invoke();
yield return null;
}
}
currentFactor = targetFactor;
image.color = targetColor;
// continue calling the whileHovered every frame
while(true)
{
whileHovered.Invoke();
yield return null;
}
}
public void OnPointerEnter(PointerEventData pointerEventData)
{
if(currentRoutine != null) StopCoroutine(currentRoutine);
currentRoutine = StartCoroutine(Fade(true));
onEnter.Invoke();
}
public void OnPointerExit(PointerEventData pointerEventData)
{
if(currentRoutine != null) StopCoroutine(currentRoutine);
currentRoutine = StartCoroutine(Fade(false));
onExit.Invoke();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536476.html
下一篇:當玩家碰撞時使物體搖晃
