Last active
August 29, 2015 14:14
-
-
Save marcteys/ed66bb23128f3b3589c8 to your computer and use it in GitHub Desktop.
Set uGUI rectTransform position from 3D object to 2D screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using System.Collections; | |
[ExecuteInEditMode] | |
public class SetPositionFromObject : MonoBehaviour | |
{ | |
public Canvas can; | |
public Camera cam; | |
public GameObject WorldObject; | |
public RectTransform UI_Element; | |
RectTransform CanvasRect; | |
void Start() | |
{ | |
CanvasRect = can.GetComponent<RectTransform>(); | |
} | |
void Update() | |
{ | |
Vector2 ViewportPosition = cam.WorldToViewportPoint(WorldObject.transform.position); | |
Vector2 WorldObject_ScreenPosition = new Vector2( | |
((ViewportPosition.x * CanvasRect.sizeDelta.x) * cam.rect.width - (CanvasRect.sizeDelta.x * 0.5f)), | |
((ViewportPosition.y * CanvasRect.sizeDelta.y) * cam.rect.height - (CanvasRect.sizeDelta.y * 0.5f)) | |
); | |
UI_Element.anchoredPosition = WorldObject_ScreenPosition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment