I add a collider for nextmeshpro in the inspector. When I left click on the textmeshpro nothing happens and the collider is null. It works fine with other objects. Tried Box Collider, Box Collider 2D, Mesh Collider.
void Start()
{
Solution = GameObject.Find("Solution").GetComponent<TextMeshPro>();
}
void Update()
if (Input.GetMouseButtonDown(0))
{
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.name == "Solution")
{
//does not enter
return;
}
}
}
}
Is this a world space UI?
If not then none of the parts involved would necessarily have anything to do with what the camera is seeing, would not even be physically where that ray goes.
I think you want other things like the IPointerClickHandler family of interfaces.
Or just stick a UI.Button on it and be done.
1 Like
Why does this work with other objects the camera is pointing at? For example cube mesh “Field”:
void Start()
{
Field = GameObject.Find("Field");
}
void Update()
if (Input.GetMouseButtonDown(0))
{
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.name == "Field")
{
//enter
return;
}
}
}
}
TextMeshPro - “Create → 3DObject → Text - TextMeshPro”
Cube - “Create → 3DObject → Cube”
I’m going to repeat Kurt’s question, is this world space UI? Or is this screen space UI?
In either case, you might want to just use a button.
1 Like
These are not UI elements. Objects are placed on the 2D SampleScene in the camera view. I don’t understand your questions.)
I just created a 2D project and placed a cube on the scene - “Create → 3DObject → Cube” and TextMeshPro - “Create → 3DObject → Text - TextMeshPro”.
Because UI behaves different than regular game objects; they can’t be plopped in and expect to behave the same as other game objects.
You want a Graphics Raycaster component on your UI rather than a collider.
1 Like
If I add an element via “Create → 3DObject → Text - TextMeshPro” will it be UI element or regular? There are two ways to add TextMeshPro
- “Create → 3DObject → Text - TextMeshPro”
- “Create → UI → Text - TextMeshPro”
Can’t find example code for using graphicraycaster for TextMeshPro With GameObject.Find("Solution").GetComponent<TextMeshPro>().GetComponent<GraphicRaycaster>();
I have added a GraphicRaycaster component to my TextMeshPro. And then I was guided by this example: Unity - Scripting API: UI.GraphicRaycaster.Raycast. But nothing works.
I don’t know what I changed. It seems that nothing has changed. But the BoxCollider method just started working. Thanks to all who responded.