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。

猜你喜欢

转载自blog.csdn.net/weixin_42399500/article/details/83747920