Skip to content

Instantly share code, notes, and snippets.

@haramakoto
Last active June 7, 2023 20:44
Show Gist options
  • Save haramakoto/10a4bafe42d99e2d61ded608089cb9ab to your computer and use it in GitHub Desktop.
Save haramakoto/10a4bafe42d99e2d61ded608089cb9ab to your computer and use it in GitHub Desktop.
UIAttachTo3DObjectSimple.cs
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