RectTransform.localPosition = Vector3 Not setting correctly
I've made a script to set a UI element by its screen position. This is being obtained correctly but the position is being set strangly, im trying to figure out why. It doesn't seem to set the position as i want it. Can someone please help.
I made a test script to do the following get the position of a gameobject. get the screen position of this position (this is just testing how the works (converting a worldspace to screenspace) Then i tried to make it set the position of an object on the canvas to these screenspace co-ordinates
The test script is as follows: using System.Collections; using System.Collections.Generic; using UnityEngine;
[ExecuteInEditMode]
public class GridPositionTest : MonoBehaviour {
private Canvas canvas;
[Header("Debug")]
public GameObject obj;
public GameObject repositionObject;
public Vector3 canvasPosition;
public Vector3 canvasOffset;
// Use this for initialization
void Start () {
canvas = GetComponent<Canvas>();
canvasOffset = canvas.transform.position;
}
// Update is called once per frame
void Update () {
canvasOffset = canvas.transform.position;
if (obj != null)
{
canvasPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, obj.transform.position);
if (repositionObject != null)
{
RectTransform rect = repositionObject.GetComponent<RectTransform>();
rect.localPosition = canvasPosition;
}
}
}
}
This is the script in the ingame editor:
This is the resulting position:
Your answer
Follow this Question
Related Questions
Prevent World Space canvas render mode to overlay other game objects 0 Answers
Sprite in Canvas not projected correctly in Maximum playmode 0 Answers
Screen Space - Camera for Mobile (Android) not working 0 Answers
How to move a camera smoothly to a fixed position and back using C#? 0 Answers
Getting all sprites to render inside of the Perspective camera 1 Answer