英文:
Unity - null reference exception error when creating new array
问题
我有一个脚本,应该生成一个随机动画数组,每当数组设置为新的动画数组时,就会出现错误。 weapons 是一个 ScriptableObject 类,其中包含一个空的动画数组。
[SerializeField]
AnimationCollections animationCollections;
public WeaponObject[] MakeWeapons()
{
WeaponObject[] weapons = new WeaponObject[2];
for (int i = 0; i < weapons.Length; i++)
{
// 这是 Unity 报告错误的地方
weapons[i].Attacks = new AnimationClip[(Random.Range(2, 5) * 2)];
weapons[i].attackBlends = new float[weapons[i].Attacks.Length / 2];
for (int z = 0; z < weapons[i].Attacks.Length; z++)
{
weapons[i].Attacks[z] = animationCollections.animations[Random.Range(0, animationCollections.animations.Length)];
if (weapons[i].attackBlends.Length < z)
{
weapons[i].attackBlends[z] = Random.Range(0f, 1f);
}
}
}
return weapons;
}
如果有人能帮助,我会非常感激!
英文:
I have a script that should be generating an array of random animations, whenever the array is set to a new animation array an error is popping up. weapons is a scriptableObject class that contains an empty animation array.
[SerializeField]
AnimationCollections animationCollections;
public WeaponObject[] MakeWeapons()
{
WeaponObject[] weapons = new WeaponObject[2];
for (int i = 0; i < weapons.Length; i++)
{
// this is where unity says the error is
weapons[i].Attacks = new AnimationClip[(Random.Range(2, 5) * 2)];
weapons[i].attackBlends = new float[weapons[i].Attacks.Length / 2];
for (int z = 0; z < weapons[i].Attacks.Length; z++)
{
weapons[i].Attacks[z] = animationCollections.animations[Random.Range(0, animationCollections.animations.Length)];
if (weapons[i].attackBlends.Length < z)
{
weapons[i].attackBlends[z] = Random.Range(0f, 1f);
}
}
}
return weapons;
}
if anyone could help i'd really appriciate it!
答案1
得分: 2
你必须初始化数组的元素,如果不这样做,它们将为null。因此,调用它们的成员将引发NullReferenceException。
你应该添加例如:
weapons[i] = new WeaponObject();
英文:
You have to initialize the elements of the array, until you do that, they will be null. Therefore invoking their members will throw a NullReferenceException.
You should add e.g
weapons[i] = new WeaponObject();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论