void UpdateUI () {
for (int i = 0; i < slots.Length; i++)
{
if (i < inventory.items.Count) {
currentSlot = GetComponentsInChildren<InventoryScroll>();
slots[i] = currentSlot;
currentSlot.AddItem(inventory.items[i]);
Debug.Log ("Updating UI");
} else
{
slots[i].ClearSlot();
}
}
}
编辑!
这是我的InventoryUI的顶部,我想将int currentSlot带到这里
public Transform itemsParent;
Inventory inventory;
InventorySlot[] slots;
// Start is called before the first frame update
void Start()
{
inventory = Inventory.instance;
inventory.onItemChangedCallback += UpdateUI;
slots = itemsParent.GetComponentsInChildren<InventorySlot>();
}
但是“清单滚动”是这种方式
List<GameObject> slots = new List<GameObject>();
public int currentSlot=0;
int slotsToScroll=3;
void Start() {
foreach(Transform child in this.transform) {
slots.Add(child.gameObject);
}
}
void Update () {
if (Input.GetKeyDown(KeyCode.Alpha1)) {
currentSlot=0;
UpdateDisplay();
}
if (Input.GetAxis("Mouse ScrollWheel") >0){
if (currentSlot<slotsToScroll) {
currentSlot++;
} else {
currentSlot=0;
}
UpdateDisplay();
}
}
void UpdateDisplay() {
for (int i = 0; i < slots.Count; i++)
{
if (i==currentSlot) {
slots[i].transform.GetChild(0).gameObject.SetActive(true);
} else {
slots[i].transform.GetChild(0).gameObject.SetActive(false);
}
}
}
库存脚本
#region Singleton
public static Inventory instance;
void Awake () {
if (instance != null) {
Debug.LogWarning("More than one instance of inventory found!");
return;
}
instance = this;
}
#endregion
public delegate void OnItemChanged();
public OnItemChanged onItemChangedCallback;
public int space = 6;
公共列表项=新的List();
public bool Add (Item item) {
if (!item.isDefaultItem) {
if(items.Count >= space) {
Debug.Log("Not enough inventory space.");
return false;
}
items.Add(item);
if (onItemChangedCallback != null)
onItemChangedCallback.Invoke();
}
return true;
public void Remove (Item item) {
items.Remove(item);
if (onItemChangedCallback != null)
onItemChangedCallback.Invoke();
答案 0 :(得分:1)
小心谨慎,Unity有两种方法:
返回
type
中类型为GameObject
的所有组件或其任何子组件。
这将返回一个InventoryScroll []
!
使用深度首先搜索返回
type
中类型为GameObject
的组件或其任何子组件。
这将返回一个单独的InventoryScroll
引用,找到的第一个引用!
请注意 s
!
从您的描述以及如何在代码中使用它来看,您似乎想使用后者,但过多使用s
。
第二个错误:从变量名听起来,您似乎想获得一个InventorySlot
不是一个InventoryScroll
!
所以您应该使用
currentSlot = GetComponentInChildren<InventorySlot>();
尽管在不查看slots
和currentSlot
的类型的情况下很难用这段代码来告诉您实际的目标。
对于我来说,您已经获得slots
中的所有Start
,但在这里您覆盖
slots[i] = currentSlot;
对于每个i
的{{1}} 。另外,您会迭代i < inventory.items.Coun
,但会传入slots.Length
..我不明白到底应该在这里发生什么。