unity 路過零件顯示名字(text跟隨,隨便變大變小)
1.畫布上新建text,text加上canvas group 和 content sizi fitter 兩個元件。
2.再加上程式碼Tooltip。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Tooltip : MonoBehaviour
{
private Text txtName;//文字
private CanvasGroup canvasGroup;//元件
private float targetAlpha = 0;//標籤提示初始透明度
private float speedAlpha = 10;//透明變換的速度
private GameObject canvas;//畫布
public Vector2 M_pos = new Vector2(-100, -40);//增加的位移
void Awake()
{
txtName = GameObject.Find("Tooltip").GetComponent<Text>();
canvasGroup = GameObject.Find("Tooltip").GetComponent<CanvasGroup>();
canvas = GameObject.Find("Canvas");
}
void Update()
{
//差值運算透明度
if (canvasGroup.alpha != targetAlpha)
{
canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, targetAlpha, Time.deltaTime * speedAlpha);
if (Mathf.Abs(canvasGroup.alpha - targetAlpha) < 0.01f)
{
canvasGroup.alpha = targetAlpha;
}
}
//跟隨滑鼠
Vector2 Position;
//這個方法是用來 把滑鼠的座標 轉化成 畫布的座標
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, null, out Position);
txtName.transform.localPosition = Position + M_pos;
}
//顯示物體
public void onXian(string name)
{
targetAlpha = 1;
txtName.text = name;
}
//隱藏物體
public void onYin()
{
targetAlpha = 0;
}
}
3.在路過的零件加上程式碼PartsName。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PartsName : MonoBehaviour
{
public string name;//物體的名字
private Transform tooltip;
public bool isXian = true;
void Start()
{
tooltip = GameObject.Find("Tooltip").transform;
}
public void OnMouseEnter()
{
if (isXian == false) return;
tooltip.GetComponent<Tooltip>().onXian(name);
}
public void OnMouseExit()
{
if (isXian == false) return;
tooltip.GetComponent<Tooltip>().onYin();
}
}
注意:
1.text的錨點。在左上角。
2.零件上要有collider。