【发布时间】:2017-10-03 13:20:20
【问题描述】:
在运行时,我首先将一些项目添加到数组中,然后将它们的值写入日志(工作正常)然后我实例化它们(仍然工作正常),然后我想更改数组项目的值,但由于某种原因,现在数组索引返回 null?有谁知道出了什么问题?
public class ListEquippedItems : MonoBehaviour
{
private static ListEquippedItems instance = null;
public static ListEquippedItems Instance
{
get
{
if (instance == null) instance = new ListEquippedItems();
return instance;
}
}
[SerializeField]
private GameObject[] currentlyEquippedItems = new GameObject[8];
void Awake()
{
// Putting fake items into the currently equipped to test that items can actually be transfered to it
for (int i = 0; i < currentlyEquippedItems.Length; i++)
{
//////////////////// In 3 below lines the array works just fine and returns proper values.
currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().SetItemType((EffectTypes)i);
currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().SetItemName("I am item: " + i);
currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().SetItemIcon(RewardAssetContainer.Instance.commonExample);
Debug.Log(currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemIcon().ToString());
Debug.Log(currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemType().ToString());
Debug.Log(currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemName());
}
}
public void SetEquippedItem(EffectTypes _itemType, Sprite _itemIcon, string _itemName)
{
for (int i = 0; i < currentlyEquippedItems.Length; i++)
{
Debug.Log(currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemType().ToString());
Debug.Log(currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemName());
Debug.Log(currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemIcon().ToString());
//////////////////// In 3 below lines the array returns null references, but why?
if (currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().GetItemType() == _itemType)
{
currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().SetItemName(_itemName);
currentlyEquippedItems[i].GetComponent<ListEquippedEntry>().SetItemIcon(_itemIcon);
break;
}
}
}
【问题讨论】:
-
我不知道你的 _itemType 的类型。但是您可以尝试添加 toString() .Like .GetItemType().toString() == _itemType.toString())
-
我已经试过了。我很确定没有其他脚本可以以任何方式访问此数组,并且游戏对象也不会被禁用或类似的东西。我不知道为什么它在我身上返回空值,但项目及其精灵在场景中仍然可见-.-
-
我没有看到您提供的代码有任何问题,您有什么办法可以发布
SetItemName、SetItemType和SetItemIcon的代码,因为它们似乎是你的ListEquippedEntry班级,我相信这可能会产生一些影响。乍一看,您的代码似乎应该可以正常工作。 -
在导致 NPE 的部分之前添加的调试语句的结果是什么?
标签: c# arrays unity3d singleton gameobject