Search Unity

Not able to get real position of an object in a Canvas with "Screen Space Overlay"

Discussion in 'UGUI & TextMesh Pro' started by Neliosam, Jul 27, 2019.

  1. Neliosam

    Neliosam

    Joined:
    Jan 18, 2014
    Posts:
    2
    I have a mobile game with a BAR on the top of the screen. The bar and it's game objects are in canvas with "Screen Space - Overlay" mode plus a Canvas Scaler with scale mode of "Scale with Screen Size" and match equals "Match width or height".

    I am animating a game object to the position of an object inside of this and the object is going completely of the screen (really far way).

    I am trying to get the position of the object using the following:

    Code (CSharp):
    1.     public Vector3 getObjectPosition()
    2.     {
    3.         // Getting my CANVAS
    4.         Camera cam = Camera.main;
    5.         GameObject canvasOverlayObject = GameObject.Find("CanvasOverlay");
    6.         Canvas canvas = canvasOverlayObject.GetComponent<Canvas>();
    7.  
    8.         //Manual scalling the CANVAS
    9.         float canvasScaleX = Screen.width / canvasOverlayObject.GetComponent<CanvasScaler>().referenceResolution.x;
    10.         float canvasScaleY = Screen.height / canvasOverlayObject.GetComponent<CanvasScaler>().referenceResolution.y;
    11.  
    12.         return Camera.main.ScreenToWorldPoint(new Vector3(transform.position.x / canvas.scaleFactor, transform.position.y / canvas.scaleFactor, 0));
    13.     }
    Even so, the position being returned is complete of the screen. Any idea what I am doing wrong?

    thanks
    Nelio
     
  2. Neliosam

    Neliosam

    Joined:
    Jan 18, 2014
    Posts:
    2
    I have found the answer. No scaling is needed in this case even in a scaled canvas.

    Code (CSharp):
    1.     public Vector3 getPosition()
    2.     {
    3.         Camera cam = Camera.main;
    4.         GameObject canvasOverlayObject = GameObject.Find("CanvasOverlay");
    5.         Canvas canvas = canvasOverlayObject.GetComponent<Canvas>();
    6.  
    7.         Vector3 rawPosition = Camera.main.ScreenToWorldPoint(gameObject.transform.position);
    8.  
    9.         return rawPosition;
    10.     }