【发布时间】:2021-11-03 20:18:54
【问题描述】:
您好,我开始在 Unity3d 中开发游戏,但我的代码或检查器中有错误。
我的错误出现在我分配 itemToEquip 两次的数组 arthursButtonsDescription 中。第一轮一切顺利 arthursButtonsDescription[0].name 是“0”,但第二轮我分配 arthursButtonsDescription[4].name=4 和 arthursButtonsDescription[0].name 也是 4,这是我的错误。
我录制了有关此错误的视频:https://youtu.be/wZuFo5uhL5o
我将我的错误项目上传到:https://uloz.to/file/zfyxYuOiHTa4/dandd-zip#!ZGp4LmR2AzV0MTSvMGxkMwOvZwEuBGEuIRuhIyM6MJAgFGIuAj==/dandd-zip
using UnityEngine;
public class Item : MonoBehaviour
{
public Sprite icon = null;
public bool showInInventory = true;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Equipment : Item
{
public EquipmentSlot equipSlot;
new public string name = "New Item";
}
public enum EquipmentSlot { Head, Chest, Legs, Foot, Shield, Weapon,
Potion20Hp, Potion40Hp, Potion60Hp, Potion80Hp, Potion100Hp,
Potion25Percent, Potion50Percent, Potion75Percent, Potion100Percent }
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveLoadStarter : MonoBehaviour
{
public void LoadClick()
{
Equipment itemToEquip = gameObject.AddComponent<Equipment>();
itemToEquip.name = "0";
itemToEquip.equipSlot = EquipmentSlot.Head;
Debug.Log("iTE0: " + itemToEquip.name);
EquipmentManager.instance.Equip(itemToEquip);
itemToEquip.name = "4";
itemToEquip.equipSlot = EquipmentSlot.Shield;
Debug.Log("iTE4: " + itemToEquip.name);
EquipmentManager.instance.Equip(itemToEquip);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EquipmentManager : MonoBehaviour
{
public static EquipmentManager instance;
public void Awake()
{
if (instance != null)
{
Debug.Log("EquipmentManager instance not equals null");
return;
}
instance = this;
}
public ArthurInventory ai;
public void Equip(Equipment newItem)
{
ai = FindObjectOfType(typeof(ArthurInventory)) as ArthurInventory;
ai.ShowArthursButtons(newItem);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ArthurInventory : MonoBehaviour
{
public GameObject[] arthursButtons/* = new GameObject[6]*/;
public Equipment[] arthursButtonsDescription = new Equipment[6];
public void ShowArthursButtons(Equipment newItem)
{
for (int i = 0; i < arthursButtons.Length; i++)
{
if (arthursButtons[i].name == "HellmButton" && newItem.equipSlot == EquipmentSlot.Head)
{
arthursButtons[i].GetComponentInChildren<Button>().GetComponentInChildren<Image>().enabled = true;
arthursButtonsDescription[0] = newItem;
}
if (arthursButtons[i].name == "ShieldButton" && newItem.equipSlot == EquipmentSlot.Shield)
{
arthursButtons[i].GetComponentInChildren<Button>().GetComponentInChildren<Image>().enabled = true;
arthursButtonsDescription[4] = newItem;
Debug.Log("AI0: " + arthursButtonsDescription[0].name);
}
}
}
}
【问题讨论】:
-
您正在将相同的对象引用分配给数组中的多个位置 -> 您实际上正在更改同一个对象的值...您的
Item类必须是MonoBehaviour在全部?