Reputation: 399
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?
Upvotes: 0
Views: 639
Reputation: 2300
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);
}
Upvotes: 1