通用代码库
基于Unity5.6.0f
实现UI跟随物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIFllow : MonoBehaviour
{
public RectTransform Img;
public Transform Player;
public Text Txt;
public GameObject Canves;
public float offset;
// Update is called once per frame
void Update()
{
//get ScreenPoint...Important
Vector2 vec2 = Camera.main.WorldToScreenPoint(transform.position);
Img.anchoredPosition =
new Vector2(vec2.x - Screen.width / 2 + 0, vec2.y - Screen.height / 2 + 60); //控制偏移量
//rectBloodPos.anchoredPosition = vec2 + new Vector2(offstex,offsety);
//Debug.Log(Player.position);
offset = Vector3.Distance(Player.transform.position, transform.position);
Txt.text = offset.ToString("#0.0");
}
//超出视野隐藏
void OnBecameVisible()
{
Canves.active = true;
}
void OnBecameInvisible()
{
Canves.active = false;
}
需要注意的是:
1.在Unity3D中测试时,需要同时满足物体也出了Scene的窗口,才可以响应OnBecameInVisible。打包成exe出来就没有这个影响。
2.OnBecameVisible和OnBecameInVisible所在的脚本是需要挂在要判断的物体上。
3.用来判断的物体是需要有Renderer Component的。
本文介绍了一种在Unity中实现UI元素跟随指定物体移动的方法,并通过代码示例展示了如何实时更新UI位置及距离显示,同时实现了超出视野时UI的自动隐藏功能。
1350

被折叠的 条评论
为什么被折叠?



