效果图放上(不断点击键盘G随机获取物品):

此篇是接着上篇背包前奏来写,拖拽和射线检测部分就不再多说,包括后面的修改加上了交换、回初始位置等功能都是在那个基础上的扩展,各有所需各自想要的扩展也就不同,大家可以根据上一篇来自己扩展。
该篇主要来介绍一下背包的拾取功能
1、创建一个image用来作为背景,命名为Beibao,比如说如下图:

2、在Beibao下添加一个空对象,命名为Grid,并为其添加Gridlayout Group组件,调整大小,符合背景。
3、在Grid下创建一个image,命名为UCell,将其做成prefab,然后做满整个Grid,当然,数量自己控制,如下图:

4、为UCell做一个子对象,命名为UItem,UItem下包含一个text,也做成prefab。当然,大小要自己设置好,至少不能比UCell大。
5、准备几个图片资源,创建一个Resources文件夹,放到下面,内容自由发挥吧,比如下图:

6、开始写脚本:
创建一个C#脚本,命名为UPickup,关键代码如下:
usingUnityEngine;
usingSystem.Collections;
usingUnityEngine.UI;
publicclass UPickup : MonoBehaviour {
publicGameObject[] cells;
publicGameObject instantiate;
GameObject item;
AudioClip Musics;
Image[] Images;
Image Imagesingle;
Text index;
intIndexInt = 0;
stringIndexStr = "";
intRandomM = 0;
stringRandomStrInt = "";
stringRandomStr = "";
// Use this for initialization
voidStart () {
}
// Update is called once per frame
voidUpdate () {
if(Input.GetKeyDown (KeyCode.G)) {
Pickup ();
}
}
publicvoid Pickup(){
boolisFind = false;
RandomM = Random.Range (0,6);
RandomStrInt = RandomM.ToString ();
RandomStr = "Pictures/"+ RandomStrInt;//路径
print (RandomStr);
item = Instantiate (instantiate, transform.position, transform.rotation) asGameObject;//获取预制物体
Imagesingle = item.transform.GetComponent<Image>(); //获取预制物体的image组件
Imagesingle.overrideSprite = Resources.Load (RandomStr, typeof(Sprite))asSprite; //动态加载image组件的sprite
for(inti = 0; i < cells.Length; i++) {
if(cells [i].transform.childCount > 0) {//判断当前格子是否有物体
//如果有,并且一样的
if(Imagesingle.overrideSprite.name == cells [i].transform.GetChild (0).transform.GetComponent<Image>().overrideSprite.name) {
//判断的是image加载图片的名字
isFind = true;
index = cells [i].transform.GetChild (0).transform.GetChild(0).GetComponent<Text>();
IndexInt = int.Parse(index.text);
IndexInt += 1;
IndexStr = IndexInt.ToString();
index.text = IndexStr;
Destroy (item);
}
}
}
if(isFind == false) {
for(inti = 0; i < cells.Length; i++) {
if(cells [i].transform.childCount == 0) {
//当前没有物体,则添加
item.transform.SetParent(cells[i].transform);
item.transform.localPosition = Vector3.zero;
break;
}
}
}
}
}
解释一下,该函数实现的功能有动态随机加载UItem图片、判断当前格子是否有物品,有就加数目,没有就添加新物品,逻辑结构应该还算清晰。
7、把脚本挂载在Grid上,并配好,如下图:

8、添加两个Tag分别为UCell和UItem

将UCell组件的Tag设为UCell,将UItem的Tag设为UItem。用作代码中作判断。
到此差不多做好了,拖拽不用多少,看过上一篇的应该都明白,有什么问题尽管问。

我把工程打了个小包,看看吧,最近有点小忙,没时间扩展了,其实还有很多地方可以扩展,比如说分页,写接口,用对象池等,本想写好了再放,这等你们自己扩展吧,导入应该就能用,如果有问题可能是标签没设置,设置好uitem和ucell选择相对应的就行