Unity c# получить значение по нажатому тексту пользовательского интерфейса - PullRequest
0 голосов
/ 06 марта 2020

Есть ли способ получить значение по нажатому тексту пользовательского интерфейса? Я пробовал это с 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?

1 Ответ

1 голос
/ 06 марта 2020

Вам нужно использовать GraphicRaycaster, а не физический raycast.

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

Это немного отличается от физики raycast в том смысле, что вы должны использовать некоторые промежуточные классы (ie. 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);
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...