I have a script that places an UI element on the place where a 3d object is in 3d space. I do this in the following way:

public class test : MonoBehaviour {

public Camera MainC;
public GameObject testc;

// Use this for initialization
void Start () {
    var ui = Object.Instantiate((GameObject)Resources.Load("uit"), Vector2.zero, Quaternion.identity);
    ui.transform.SetParent(GameObject.FindObjectOfType<Canvas>().gameObject.transform, false);

    var vertexs = testc.GetComponent<MeshFilter>().mesh.vertices;
    var trs = testc.GetComponent<Transform>();
    var cdc = new Vector2(GameObject.FindObjectOfType<Canvas>().GetComponent<RectTransform>().sizeDelta.x , GameObject.FindObjectOfType<Canvas>().GetComponent<RectTransform>().sizeDelta.y); 

    Object.Instantiate((GameObject)Resources.Load("pinksphere"), trs.transform.TransformPoint(vertexs[6]), Quaternion.identity); //bottomright
    Object.Instantiate((GameObject)Resources.Load("pinksphere"), trs.transform.TransformPoint(vertexs[5]), Quaternion.identity); //topleft

    var tl = MainC.WorldToViewportPoint(trs.transform.TransformPoint(vertexs[5]));

    var topleft = new Vector2(tl.x * cdc.x, tl.y * -(cdc.y) );
    ui.GetComponent<RectTransform>().anchoredPosition = topleft;


But this does not place the UI Element on the desired position. See the following images for more explaination.

enter image description here

in this case i want the TOPLEFT corner of the UI element to be ontop of the pink dot at the TOPLEFT of the whitecube. But as you can see the Y-axis doesnt quite match..

Some extra information about the conditions like canvas used and the prefab settings. See images below:

enter image description here these are the canvas settings.

enter image description here this are the Main Camera settings.

enter image description here and this are the UI prefab settings.

If you need any more information or something isnt clear let me know so i can clarify!
the code is really inefficient and ugly but it is only for testing purposes :)

  • \$\begingroup\$ Usually you'd want to parent a new UI element to the canvas, or to an existing UI element under the canvas, and set its AnchoredPosition as described in this related Q&A — have you tried something like that? \$\endgroup\$ – DMGregory Aug 30 '18 at 10:38
  • \$\begingroup\$ good suggestion about setting the parent first. I changed the code see updated question. But i still have the exact same problem.. \$\endgroup\$ – FutureCake Aug 30 '18 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.