这篇文章介绍如何更换图片还有提示显示,话不多说,直接上代码和效果图
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UGUI.Tool;
using System.Collections.Generic;
//背包管理
public class KnapsackManager : MonoBehaviour {
public static KnapsackManager _instance;
public bool isShow = true; //是否显示
public List<GameObject> listParent = new List<GameObject> (); //生成格子存到列表
public List<Sprite> itemSprite = new List<Sprite>();
public List<int> price = new List<int> ();
[SerializeField]
public Text myText;
private GridLayoutGroup grid; //生成的格子的父类
private GameObject itemParent; //格子
private GameObject item; //物品
void Awake(){
_instance = this;
}
// Use this for initialization
void Start () {
grid = transform.Find ("BG/Grid").GetComponent<GridLayoutGroup>();
itemParent = Resources.Load<GameObject> ("Prefabs/ItemParent");
item = Resources.Load<GameObject> ("Prefabs/Item");
myText = transform.Find ("Text").GetComponent<Text>();
SetKanspackGridLayout ();
}
// Update is called once per frame
void Update () {
//按下x件生产背包物品
if(Input.GetKey(KeyCode.X)){
SetItem (Random.Range(0,itemSprite.Count));
}
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle (this.GetComponent<RectTransform>(),Input.mousePosition,null,out position);
if (isShow) {
myText.gameObject.SetActive (true);
SetPosition (position);
} else {
myText.gameObject.SetActive (false);
}
}
//背包布局
void SetKanspackGridLayout(){
for (int i = 0; i < 20; i++) {
GameObject go = GameObject.Instantiate (itemParent, transform.position, Quaternion.identity) as GameObject;
go.transform.parent = grid.transform;
listParent.Add (go);
}
}
void SetItem(int id){
myText.text = "售价:" + price [id].ToString ();
foreach(GameObject go in listParent){
if(go.transform.childCount == 1){
GameObject myItem = UguiTool.OnAddTool (go,item);
myItem.GetComponent<Item> ().SetIcon (id);
break;
}
}
}
public void SetPosition(Vector2 position){
myText.rectTransform.anchoredPosition = position;
}
}
这个代码要挂在item上,如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Item : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void SetIcon(int id){
this.GetComponent<Image> ().sprite = KnapsackManager._instance.itemSprite [id];
}
public void OnPointerEnter(PointerEventData data){
KnapsackManager._instance.isShow = true;
}
public void OnPointerExit(PointerEventData data){
KnapsackManager._instance.isShow = false;
}
}
效果图: