- Home /
Rect Transform local position to gameobject position
I get the local position within a rect transform and save it for later use.
// Rect transform bounds RectTransform rt = gameObject.GetComponent ();
// Localpoint RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, mousepos, Camera.main, out output); Vector2 localpoint = output;
Now I would like to use this local-point output to instantiate another gameobject to this location but I can't figure how to convert it for gameObject.position so that the game object would appear in the same spot as where the mouse-click was.
I'm pretty sure that you can use ScreenToWorldPoint to convert UI coordinates to world coordinates. I'm doing this in a 2D game, and it's working very well. It may not work quite as well in a 3D game since Screen coordinates do not have a Z-Value.
Answer by Mmmpies · Dec 25, 2014 at 11:30 PM
@RedHedZed is right but I think it'll work differently in 3D. The test I did for another question is this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class RectUtil : MonoBehaviour {
public Camera MainCam;
public RectTransform myRectT;
private Vector3 result;
//ScreenPointToWorldPointInRectangle(rect: RectTransform, screenPoint: Vector2, cam: Camera, worldPoint: Vector3): bool;
// Use this for initialization
void Start () {
Vector2 myV2 = new Vector2(0,24);
Debug.Log (RectTransformUtility.ScreenPointToWorldPointInRectangle(myRectT,
myV2,
MainCam,
out result));
Debug.Log (result);
}
}
the output returns 0 on the Z. I haven't tried this but I suspect you'll need to record the camera transform before going into the new UI and then use the results to add to that transform.
You'll also need to deal with depth but test the output of that code.
Switch from 3D to 4.6 GUI and in 3D move around and see if the values change for that (randomly selected) 0,24 Vector2 when you go into the menu.
If it does (significantly) then movement in 3D makes a difference, if not then recording the camera transform before going into the 4.6 menu and use the output information to add to that transform.
That came out a lot more complicated than I intended. Hope you understand!
Your answer
