The following UnityScript worked fine when attached on the old GUI Text.
But it does not work when attached to a new UI Text which is a child of my new canvas.
Can someone tell me why it does not work?
function Update () {
// Get the ray going through the GUI position
var ray : Ray = Camera.main.ViewportPointToRay(transform.position);
// Do a raycast
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)){
//print ("I'm looking at " + hit.transform.name);
//print ("I'm looking at " + hit.transform.tag);
}
}
The “new” Canvas system uses RectTransform instead of Transform, so create a reference to the RectTransform of the text and use its position instead of transform.position.
Yeah, I don’t think what @Team2Studio suggested will work - draw a debug ray and you will see it is not in correct position.
IMO uGUI Canvas is really convoluted to use. If you have Screen space canvas, it is located in world space 0,0,0 and spans to positive direction in X and Y axis. And the transform values for rectTransform are world values, but those are usually not constant. If you have screen pixel size of 600x300, then your canvas will have the same pixel size, and actually rectTransform.position will show these values in meters/unity units. Placing rt on right edge will show its (world) .position to be at 600 units. But this will change as soon as you change the editor game view size. And you can’t convert AFAIK these values with ViewportPointToRay.
I have now changed “ViewportPointToRay” to “ScreenPointToRay” and now it works
function Update () {
// Get the ray going through the GUI position
var rect : Vector3 = GetComponent.<RectTransform>().position;
var ray : Ray = Camera.main.ScreenPointToRay(rect);
// Do a raycast
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)){
//print ("I'm looking at " + hit.transform.name);
//print ("I'm looking at " + hit.transform.tag);
}
}
And be aware, this will most likely only work with “Screen Space - Overlay” Canvas - not with “Screen Space - Camera” canvas. Because of above mentioned thing (world space coordinates match screen coordinates).
I am still using Unity 2017.4.33f1 and Unity scripts are working fine. But you are right its time to convert to C#. Its just because I have tons of old Unity scripts because I have started with them