-3

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!

  • Does this answer your question? [Avoiding null reference exceptions](https://stackoverflow.com/questions/1943465/avoiding-null-reference-exceptions) – Louis Ingenthron Feb 19 '23 at 17:00

1 Answers1

2

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();
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46