Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question WorldToScreenPosition Not working

Discussion in 'Scripting' started by bearejustin, Apr 28, 2021.

  1. bearejustin

    bearejustin

    Joined:
    Mar 6, 2021
    Posts:
    9
    Hi all I am trying to get the position of a gameobject in terms of ui position and I have been told to use worldtoscreenposition, however when i try to use it like this:

    Code (CSharp):
    1. Vector2 ScreenPos = RectTransformUtility.WorldToScreenPoint(Camera.main,GameObject.Find(xsquare + "x" + ysquare).transform.position);
    2. RectTransformUtility.ScreenPointToLocalPointInRectangle(PieceRect,ScreenPos,null, out CanvasPos);
    3. PieceRect.anchoredPosition = CanvasPos;
    It doesn't get the same position at all, I have my canvas set to screen space - overlay.
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,832
    I notice that you're setting the position of PieceRect based on the local position of the point relative to PieceRect, which is almost certainly not what you want. You probably want the location in the coordinates space of PieceRect's parent.

    And then you probably want to set PieceRect's localPosition rather than anchoredPosition, since the coordinates you just calculated are a local position. Though this may depend on how your anchors are set up and exactly what visual effect you're going for. Positioning RectTransforms in script is confusing.

    Regardless, it would be a good idea to take a look at intermediate results (e.g. Debug.Log(ScreenPos)) and do a manual check to see whether they're approximately what you expect. By checking your results at each step of the calculation, you can figure out the first step of the calculation where things go awry, which is often a great help in narrowing down the source of a problem.
     
    Kurt-Dekker likes this.
  3. bearejustin

    bearejustin

    Joined:
    Mar 6, 2021
    Posts:
    9
    Thanks I made the location in the coordinates space to be the PieceRects parent and it worked, thanks for the help.