简体   繁体   中英

Unity c# get value of clicked ui text

Is there a way to get the value of a clicked ui text? I tried it with RaycastHit, but nothing happens.

This is my code:

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 !! ");
    }
}

If I click for example on txt1 , I want that the value of txt1 will be added to txtHeadline . But every time I click anywhere my output is Nothing happens !! .. what is wrong with my raycasthit?

You need to use the GraphicRaycaster, not the physics raycast.

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

It's quite a bit different from physics raycast, in that you have to utilize some intermediate classes (ie. PointerEventData ) and it returns a list of hits not just one.

Also, it doesn't seem to be listed in the 2019.3 docs. The link above is for the 2019.1 docs. I wouldn't be surprised to see it deprecated in the near future.

An excerpt from the above docs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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