Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Coordinates in-game is different from the unity editor

Discussion in 'UGUI & TextMesh Pro' started by unity_BD1000D08C18D3028A82, Nov 21, 2022.

  1. unity_BD1000D08C18D3028A82

    unity_BD1000D08C18D3028A82

    Joined:
    Nov 16, 2022
    Posts:
    16
    I've running into a problem where the coordinates inside the canvas while playing the game is different from the outside
    (from inside, (0,0) is in the left-bottom corner, from outside, (0,0) is on the center)

    I can't just put the left-bottom corner of the canvas on the center of the editor because I don't know exactly how big will be the screen that will play the game, and when I stretch the canvas by the sides, both extremes get stretched ( I think it would work if could stretch only the right side)

    So, when I instantiate an object, I get the mouse coordinates in the canvas, which is different from the outside.

    My Canvas Render Mode is set to "Screen Space - Camera"

    here it is the code that instantiate the object
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class ClickStart : MonoBehaviour
    7. {
    8.     public GameObject prefab;
    9.     int count = 0;
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.      
    14.         // if mouse button down
    15.         if ((Input.GetMouseButtonDown(0)) && (count == 0))
    16.         {
    17.             // get mouse position
    18.             Vector3 mousePos = Input.mousePosition;
    19.          
    20.             //instantiates a new object at the mouse position
    21.             GameObject p = Instantiate(prefab, mousePos, Quaternion.identity);
    22.             //set parent to canvas          
    23.             count = 1;
    24.          
    25.         }
    26.  
    27.     }
    28. }
    29.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,930
    Realize that there are many different coordinate systems in play:

    - screen
    - canvas (and this has many possibilities based on Canvas and Canvas Scaler settings)
    - world

    Identify clearly what you are doing. It looks like your code above presumes screen space equals canvas space and that is most certainly not the case.

    Also checkout the RectTransformUtility class for some extra helpers.