【问题标题】:Raycast not detecting custom Unity UI button scriptRaycast 未检测到自定义 Unity UI 按钮脚本
【发布时间】:2021-03-21 13:04:09
【问题描述】:

我编写了一个自定义类来创建可以有动画师的按钮。但是这个类的对象不能被光线投射检测到,但是普通的 Unity UI 按钮可以被光线投射检测到。我正在寻找可以通过代码解决的解决方案。

public class AnimatedButton : UIBehaviour, IPointerClickHandler
{
    [Serializable]
    private class ButtonClickedEvent : UnityEvent
    {
    }

    public bool Interactable = true;

    [SerializeField]
    private ButtonClickedEvent onClick = new ButtonClickedEvent();

    private Animator animator;

    private bool blockInput;

    protected override void Start()
    {
        base.Start();
        animator = GetComponent<Animator>();
    }

    public virtual void OnPointerClick(PointerEventData eventData)
    {
        if (!Interactable || eventData.button != PointerEventData.InputButton.Left)
            return;

        if (!blockInput)
        {
            blockInput = true;
            Press();
            // Block the input for a short while to prevent spamming.
            StartCoroutine(BlockInputTemporarily());
        }
    }

    public void Press()
    {
        if (!IsActive())
            return;

        animator.SetTrigger("Pressed");
        StartCoroutine(InvokeOnClickAction());
    }

    private IEnumerator InvokeOnClickAction()
    {
        yield return new WaitForSeconds(0.1f);
        onClick.Invoke();
    }

    private IEnumerator BlockInputTemporarily()
    {
        yield return new WaitForSeconds(0.5f);
        blockInput = false;
    }
}

以下代码用于通过发射光线投射找到游戏对象

private bool checkButtonClick()
{
    bool flag = false;
    PointerEventData pointer = new PointerEventData(EventSystem.current);
    List<RaycastResult> raycastResult = new List<RaycastResult>();
    
    pointer.position = Input.mousePosition;
    EventSystem.current.RaycastAll(pointer, raycastResult);
    foreach (RaycastResult result in raycastResult)
    {
        if (result.gameObject.GetComponent<Button>() != null || result.gameObject.GetComponent<AnimatedButton>() != null)
        {
            Debug.Log("Button Name : " + result.gameObject.name);
        }
    }
    raycastResult.Clear();
    return flag;
}

仅使用此日志打印“按钮”类型的对象,并且未检测到“动画按钮”类型的对象。这可能是什么问题以及如何解决?

【问题讨论】:

    标签: c# unity3d raycasting


    【解决方案1】:

    你已经接近了。但它不是UIBehaviour,实际上是UnityEngine.UI.Graphic,派生自UIBehaviour,由GraphicRaycaster 搜索。因此,您应该能够从Graphic 派生,并且您的新按钮类型将在光线投射结果中找到。这是与 Graphic 类相关的 Unity docs。引用该页面:

    所有可视化 UI 组件的基类。

    在创建可视化 UI 组件时,您应该从此类继承。

    【讨论】:

    • 谢谢你,你是对的。但是当我尝试从 Graphic 继承时,我面临的问题是我遇到了画布渲染器未附加到对象的异常。如果我尝试添加一个画布渲染器运行时,在某些情况下,我会得到一个类似于按钮的白色边框。那么有没有其他的方法呢?
    • @Zenhal 我不太确定为什么您会在某些项目周围出现白色边框。那是你的下一个问题吗?对不起,当你问“有没有其他方法解决它”时,我不太确定你在问什么。我们还可以看看为什么要从这样一个低级别的类中创建一个新项目 AnimamtedButton。您能否改为扩展Button,甚至扩展UnityEngine.UI.Selectable
    猜你喜欢
    • 2020-08-19
    • 2020-11-14
    • 1970-01-01
    • 2023-04-09
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多