接着上篇继续加功能建立一个脚本拖动给 背景bg上,然后根据需求设定cells和Equipmentname的size,按照如图分别设定其属性,。Equipmentname是不能拖动的只能把sprite的名字输入进去。这个地方的item要把wuping的perfeb拖进去。。。。
这个是要拖给bg的脚本:
using UnityEngine;
using System.Collections;
public class Add_Equip : MonoBehaviour {
public GameObject []cells;
public string [] equipmentname;
public GameObject item;
void Update()
{
//点击键盘X捡到物品添加到背包里
if (Input.GetKeyDown(KeyCode.X))
{
Debug.Log("111111111111");
Pickup();
}
}
public void Pickup()
{
int index = Random.Range(0, equipmentname.Length);
string name = equipmentname[index];
bool isFind = false;//默认没有找到物品
for (int aa = 0; aa < cells.Length; aa++)
{
if (cells[aa].transform.childCount == 0)//若cell里面没有物品
{
Debug.Log("添加物品");
GameObject go = NGUITools.AddChild(cells[aa], item);
go.GetComponent<UISprite>().spriteName = name;
go.transform.localPosition = Vector3.zero;
break;//每当添加一个就break实现的是一次添加一个
}
else if (cells[aa].transform.childCount > 0)//若格子里有物品
{
wuping item = cells[aa].GetComponentInChildren<wuping>();
Debug.Log("cell里的物品");
if (item.sprite.spriteName == name)//如果添加物品名字是否与现在存在的一样
{
Debug.Log("Sprite名字" + name);
isFind = true;
item.AddCount();//调用AddCount方法
break;
}
}
}
}
}
调用的Addcount方法在下面wuping脚本里(上篇博客的wuping脚本修改):
using UnityEngine;
using System.Collections;
public class wuping : UIDragDropItem {
public UISprite sprite;//显示图像
public UILabel uilabel;//显示数量
private int count=1;
public void AddCount(int number = 1)//数量默认是1
{
count += number;
uilabel.text = count + "";//+“”表示空串将int型的count转化为String类型
}
protected override void OnDragDropRelease(GameObject surface)
{
base.OnDragDropRelease(surface);
print(surface);
if (surface.tag == "cell")//若拖到的是空格子里
{
this.transform.parent = surface.transform;//拖动wuping放到cell时,让格子(现在的是surface也就是cell)成为所选物体的parent。
this.transform.localPosition = Vector3.zero;//所选物体的local坐标,实现的是放到格子里是放到格子位置的中心。
}
else if (surface.tag == "wuping")//若拖到的是已经放了物体的格子里,也就是格子里已有wuping了。
{
Transform parent = surface.transform.parent;
surface.transform.parent = this.transform.parent;//保留还没有移动wuping前wuping目前所在的cell
surface.transform.localPosition = Vector3.zero;//保留还没有移动wuping前wuping目前所在的cell的位置
this.transform.parent = parent;//新的cell成为移动后的wuping的cell(也就是交换wuping)
this.transform.localPosition = Vector3.zero;
}
}
}
然后看运行,根据代码看只要按键盘X键就可以添加东西了,点击之后发现并没有出现sprite但是物品的个数是在变化的。然后看一下添加的物品的Sprite属性,发现名字在变化而且就是我们刚才在equipmentname里面添加的名字,说明确实在变化而且也添加到了cell里,只是看不到Sprite 的显示图片。这个怎么办?偶目前还未解决。待完成……
运行结果如图: