关于NGUI中UISprite的一个小bug

最近学习NGUI时发现一个小bug:由预制对象生成的精灵代码修改图片后在鼠标进入后失去焦点后会变回预制对象精灵图片

左上角精灵用于展示被点击的精灵图片

图一:正中央用预制对象生成的精灵在鼠标未进入时


图二:当鼠标进入精灵后离开


为此,我们在预制对象的脚本上只需在初始化状态下保存精灵名,在鼠标失去焦点后重新设置精灵名即可。具体控件和代码对于脚本如下:


左上角精灵

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
    private UISprite show;//展示随机生成图片大图
    public static Test _test;
    //初始化单例及获取精灵
 void Start () {
        _test = this;
        this.show = this.GetComponent<UISprite>();
 }
    //修改展示图片
    public void Show(string spriteName)
    {
        this.show.spriteName = spriteName;
    }
 
}


空对象,用于控制卡牌生成


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestRanndom : MonoBehaviour {
 
    public GameObject cartPre;//卡牌预制对象
   
 void Update () {
        if (Input.GetKeyDown(KeyCode.A))
        {
            CreateCart();
        }
 }
    void CreateCart()
    {
        string name = "cart-1-1-1-1";//精灵已在图集中
       GameObject go=     NGUITools.AddChild(this.gameObject, cartPre);//由卡牌预制对象创建
       go.GetComponent<UISprite>().spriteName = name;//修改由预制对象创建的精灵
    }
}

预制对象

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestClick : MonoBehaviour {
    private UISprite sprite;//每个由预制对象克隆的游戏精灵
    private string spriteName;//保存生成时的精灵名
    //获取自身精灵及保存程序更改的精灵名
    void Start()
    {
        this.sprite = this.GetComponent<UISprite>();
        this.spriteName = this.sprite.spriteName;
    }
    //鼠标单击
    void OnClick()
    {
        Test._test.Show(this.sprite.spriteName);
    }
    //鼠标焦点
    void OnHover(bool isOver)
    {
        if (!isOver)
        {
            print("鼠标离开精灵");
            this.sprite.spriteName = this.spriteName;
        }
    }
//精灵被点击后再点击其他精灵时失去选择也会变回预制对象图片
    void OnSelect(bool isSelected)
       {
           if (!isSelected)//精灵未选中
           {
               this.sprite.spriteName = this.spriteName;
           }
       }


这样我们就可以避免这个小bug啦。





猜你喜欢

转载自blog.csdn.net/qq511714326/article/details/80766466
今日推荐