Unity 3D - UGUI 显示道具信息

本文介绍如何使用Unity3D的UGUI系统实现道具信息提示功能。当鼠标悬停在道具上时,会显示一个跟随鼠标移动的提示框,展示道具的相关信息。实现方式包括接口继承、委托调用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity 3D - UGUI 显示道具信息 :

显示效果 :

字符串排版处理 - 链接

这里写图片描述

Demo 实现效果 :

鼠标放到道具上 , 会显示出图中提示信息 , 提示信息面板会跟随鼠标移动 , 鼠标离开道具时 , 提示信息面板会自动隐藏 .

实现过程 :

先在道具脚本上继承接口 IPointerEnterHandler 和 IPointerExitHandler .
在鼠标移动到道具上时 , 通过委派调用 OnEnter 方法 , 传入transform .

C# 代码 :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.EventSystems;
using System;

public class GridUI : MonoBehaviour, IPointerEnterHandler,IPointerExitHandler
{

    public static Action<Transform> OnEnter;
    public static Action OnExit;

    public void OnPointerEnter(PointerEventData eventData)
    {
        if (OnEnter != null) 
        {
            OnEnter (transform);
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if (OnExit != null) 
        {
            OnExit ();
        }
    }
}

Manager类处理 .

//先添加回调函数
void Awake()
{
    GridUI.OnEnter += GridUI_OnEnte;
    GridUI.OnExit += GridUI_OnExit;
}


public void GridUI_OnEnte(Transform gridTransfrom){
    //获取道具信息
    Item item = ItemModel.GetItem (gridTransfrom.name);

    //通过道具信息得到需要显示的字符串
    string str = GetItemInfoStr (item);

    //显示提示框
    isShow = true;
    itemtip.gameObject.SetActive (true);

    //用字符串刷新提示框里文本信息
    itemtip.refreshInfo (str);

}

public void GridUI_OnExit(){
    //隐藏提示框
    isShow = false;
    itemtip.gameObject.SetActive (false);
}

然后在Update中 , 让提示框跟随移动 .

void Update ()
{
    //如果处理显示状态
    if (isShow == true) 
    {
        //获取鼠标位置
        Vector2 position;
        RectTransform rect = GameObject.Find ("Canvas").transform as RectTransform;
        Vector2 point = Input.mousePosition;
        RectTransformUtility.ScreenPointToLocalPointInRectangle (rect, point, null, out position);

        //设置提示框位置
        itemtip.transform.localPosition = position;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值