Unity3d

前期工程实现了物品添加和移动功能,但是背包系统还差一个功能——物品信息提示,现在我们开始构建物品信息提示功能。

思路:建立一个Label,向Label中添加text。实现几个功能:①text显示物品的信息(核心);②Label跟随鼠标移动;③Label在鼠标移动到物品上时才显示。

好了,现在开始进行创建。

1、物品信息的显示:思路:读取物品的信息,将物品信息赋值给text,脚本如下:

Class InventoryDes

{

    public InventoryDes _instance;

    private UILabel label;

    private float timer = 0;

    void Start()

    {

        _instance = this;

        label = GetCompnentInChildren<UILabel>();

        gameObject.SetActive(false);

    }

    void Update()

    {

        if(gameObject.activeInHierarchy == true)

        {

            timer -= Time.DeltaTime;

            if(timer <= 0)

            {

                 gameObject.SetActive(false);

            }

        }

    }

    public void Show(int id)

    {

         gameObject.SetActive(true);

         timer = 0.1f;

         ObjectInfo info = ObjectsInfo._instace.GetObjectInfoById(id);

         string des = "";

         switch( info.Type )

         {

             case ObjecyType.Drug:

             des = GetDrugDes(info);

             break;

         }

         label.text = des;

    }

    string GetDrugDes( ObjectInfo info )

    {

        string  str = "";

        str += "名称:" + info.name + " ";
        str += "+HP:" + info.hp + " ";
        str += "+MP:" + info.mp + " ";
        str += "出售价:" + info.price_sell + " ";
        str += "购买价:" + info.price_buy + " ";

        return str;

    }

}

这样就可以将Label的信息显示为物品信息了,并且当Label被创建后,如果没有事件响应,会在0.1秒后消失。

2、Label随着鼠标移动而移动

在Class InventoryDes的void Show()方法中进行添加如下语句:

this.transform.position = UICamera.currentCamera.ScreenToWorldPoint(Input.mousePosition);

这样Lable就会随着鼠标移动了。

3、Label在鼠标移动到物品上才会显示

主要需要事件的监听语句。

首先在InventoryItem的prefabs中加入UI Event Listener组件,实现事件响应的先决条件。

之后在InventoryItem的prefabs中加入UI Event Trigger组件,对其中的OnHoverOver和OnHoverOut事件进行注册

在InventoryItem中添加脚本如下:

Class InventoryItem

{

    private bool isShow = false;

    public void OnHoverOver( )

    {

        isShow = true;

    }

    public void OnHoverOut( )

    {

        isShow = false;

    }

    private int id;

    public SetIconName(int id, string icon_name) //注:需要将InventoryGrid中的调用的方法将id赋值

    {

         sprite.SpriteName = icon_name;

         this.id = id;

    }

    void Update( )

    {

         if(isShow)

        {

             InventoryDes._instance.Show(id);

        }  

    }

}

原文地址:https://www.cnblogs.com/yanbenxin/p/5843629.html