This one is properly crazy - I’m using a fairly standard practice of ending my enum lists with a ‘maxValue’ entry, so I can easily create arrays using that value which resize as the enum list changes. This has been working fine, but suddenly today I hit play and am getting index out of bounds errors where it shouldn’t be possible.
So the code - I have this enum:
public enum DamageType
{
// general damaging types
none, fire, slice, crush, physical, pierce, ice, spirit, nature, light, dark, death, energy, explosive,
// special types
healing, blinding,
// generic magic resistance
magic,
// custom type for room spawning
roomBuilder,
maxValue
}
and in a class I have this variable:
public float[] damageModifiers = new float[(int)DamageType.maxValue];
also in this class I call a method to set the defaults:
public virtual void setDefaults()
{
// set default values in case they are left blank in the ini
Debug.Log("dmg type max value is " + (int)DamageType.maxValue);
for (int i = 0; i < (int)DamageType.maxValue; ++i)
{
Debug.Log("Setting dmg mod default for " + (DamageType)i + " (" + i + ")");
damageModifiers *= 1f;*
-
}*
- }*
I’ve added in the debug logs to help track down the issue. So the console output now is:
dmg type max value is 18
Setting dmg mod default for none (0)
Setting dmg mod default for fire (1)
// … //
Setting dmg mod default for magic (16)
Setting dmg mod default for roomBuilder (17)
IndexOutOfRangeException: Array index is out of range.
Character.setDefaults () (at Assets/Scripts/Behavioural/Character.cs:959)
This is crazy. It’s not only a very standard practice, but has been working great for ages. It went wrong after I added a new enum to the list (it was ‘magic’ not that it should matter). Now even if I remove magic from the list it still bombs out.
This should not happen. All I can think is that somehow Unity is not re-compiling properly and is keeping the value of ‘maxValue’ as 17 when it should now be 18. But that wouldn’t explain why it fails when I remove ‘magic’ form the list.
I also tried setting maxValue=64, but it still bombs out on ‘roomBuilder’ (index 17). The debug output did show maxValue as 64 though, so I have no idea how the array could only be 17 elements long!
Is there a way in Unity to ‘clean’ the compiled object files? (Like in Visual Studio you can go to Project->clean and it will remove all intermediate compile data).
Or does anyone have an idea why this is happening?