通用代码库
基于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的。