Last active
June 7, 2023 20:44
-
-
Save haramakoto/10a4bafe42d99e2d61ded608089cb9ab to your computer and use it in GitHub Desktop.
UIAttachTo3DObjectSimple.cs
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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
[RequireComponent(typeof(RectTransform))] | |
/// <summary> | |
/// 3DオブジェクトにUI張り付かせるやつ、ScreenSpace-Overay用 | |
/// </summary> | |
public class UIAttachTo3DObject : MonoBehaviour | |
{ | |
[SerializeField] | |
private Transform targetTransform; | |
[SerializeField] | |
private Camera targetCamera; | |
[SerializeField] | |
private RectTransform selfRectTrans; | |
private bool inited; | |
public void Init(Transform target, Camera targetCam, Camera uiCam, RectTransform canvasRect) | |
{ | |
targetTransform = target; | |
targetCamera = targetCam; | |
selfRectTrans = GetComponent<RectTransform>(); | |
inited = true; | |
} | |
void Update() | |
{ | |
if(inited) | |
{ | |
AttachPosition(); | |
} | |
} | |
private void AttachPosition() | |
{ | |
Vector3 screenPos = targetCamera.WorldToScreenPoint(targetTransform.position); | |
this.rectTransform.position = screenPos; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment