- Home /
v4.6 UI Element's Positioning Incorrect
Hello, I am writing a script that allows a cursor UI Element to follow an ingame object. The purpose of this is to allow me to control the cursor with both a gamepad and a mouse. Here is the code (Attaches to the UI Element):
using UnityEngine;
using System.Collections;
public class CursorController : MonoBehaviour
{
public Transform lookAtPoint;
public Camera playerCamera;
void Update()
{
//This value is correct.
Vector3 position = Camera.main.WorldToScreenPoint(lookAtPoint.position);
Debug.Log(position);
//This sets the UI object to a very wrong position.
GetComponent<RectTransform>().position = position;
Debug.Log(GetComponent<RectTransform>().position);
//This is more accurate but still off.
GetComponent<RectTransform>().localPosition = position;
Debug.Log(GetComponent<RectTransform>().localPosition);
//If you run the code, you will likely notice that all of the Debug Logs write the same values, despite the values not being the same in practice.
}
}
The lookAtPoint GameObject is working perfectly, according to the Debug Console, so should the cursor. The cursor used to work and then today I opened Unity and is has stopped working. If anyone can help it will be greatly appreciated. Thanks!
,Is your canvas render mode set to Overlay, world space or camera?
Canvas is set to screen space - camera, I cant use overlay because I am setting up slit screen, however tested with overlay, still doesn't work.
Answer by wowipop · Dec 26, 2014 at 04:35 AM
Easiest way is to set your canvas to Overlay, then set the anchor of the recttransform to lower left and
Vector3 position = Camera.main.WorldToScreenPoint(lookAtPoint.position);
GetComponent<RectTransform>().position = new Vector2(position.x,position.y);
Your code and suggestions work for the cursor, but not the rest of the UI, to fix this I moved the cursor to a separate canvas that uses screen-overlay and the rest of the UI sits in a screen-camera, the cursor stays where it needs to and the UI moves with the camera to allow for splitscreen, thanks!
Because this script only move the RectTransform that is attached to. and the CursorController is attached to the cursor.