繁体   English   中英

unity c# 获取被点击的 ui 文本的值

[英]Unity c# get value of clicked ui text

有没有办法获取点击的 ui 文本的值? 我用 RaycastHit 尝试过,但没有任何反应。

这是我的代码:

Text txt1, txt2, txt3;

string textValue;

private void Awake()
{
    txtHeadline = GameObject.Find("InformationFields/txtHeadline").GetComponent<Text>();

    txt1 = GameObject.Find("TextFields/txtField1").GetComponent<Text>();
    txt2 = GameObject.Find("TextFields/txtField2").GetComponent<Text>();
    txt3 = GameObject.Find("TextFields/txtField3").GetComponent<Text>();
}

void Update()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit))
    {
        // I know this might be wrong - but the code never reach this part.
        textValue = hit.collider.gameObject.name

        // How can I save the value from the clicked UI Text to textValue ?

        if(textValue != null)
        {
            Debug.Log("Text Value = " + textValue);
            txtHeadline.text = textValue;
        }
        else
        {
            Debug.Log("Text Value = null");
        }
    }
    else
    {
        Debug.Log("Nothing happens !! ");
    }
}

例如,如果我单击txt1 ,我希望将 txt1 的值添加到txtHeadline 但是每次我点击任何地方时,我的输出都是Nothing happens !! .. 我的 raycasthit 有什么问题?

您需要使用 GraphicRaycaster,而不是物理光线投射。

https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.GraphicRaycaster.Raycast.html

它与物理光线投射有很大不同,因为您必须使用一些中间类(即PointerEventData )并且它返回一个命中列表而不仅仅是一个。

此外,它似乎没有列在 2019.3 文档中。 上面的链接适用于 2019.1 文档。 看到它在不久的将来被弃用,我不会感到惊讶。

摘自上述文档:

       //Set up the new Pointer Event
        m_PointerEventData = new PointerEventData(m_EventSystem);
        //Set the Pointer Event Position to that of the mouse position
        m_PointerEventData.position = Input.mousePosition;

        //Create a list of Raycast Results
        List<RaycastResult> results = new List<RaycastResult>();

        //Raycast using the Graphics Raycaster and mouse click position
        m_Raycaster.Raycast(m_PointerEventData, results);

        //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
        foreach (RaycastResult result in results)
        {
            Debug.Log("Hit " + result.gameObject.name);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM