Unity – 创建新数组时出现空引用异常错误

huangapple go评论67阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2023年2月19日 23:49:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定