Hi. I’m trying to create an array of all available weapons and buffs. Since they are for reference only I made them static. The weapons are meant to carry a list of buffs in them. Those are applied in the constructor of the Weapon. This alone works fine. However if I try to create a buff from my static reference array I get a null reference exeption:
NullReferenceException: Object reference not set to an instance of an object
WeaponList.CreateBuff (Int32 index) (at Assets/Scripts/Weaponry/WeaponList.cs:20)
Weapon…ctor (System.String name, Single dmg, Single delay, Single sAngle, Single pSpeed, System.String prefabLoadPath, System.Int32 newBuffs, Boolean pierce) (at Assets/Scripts/Weaponry/Weapon.cs:38)
WeaponList…cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for WeaponList
WeaponSystem.Start () (at Assets/Scripts/Weaponry/WeaponSystem.cs:12)
This is extremely wierd since I use exactly the same technique to create my weapon.
Some Code Snipets:
public static class WeaponList{
private static Weapon[] availableWeapons = new Weapon[]{
new Weapon(/*stuff*/, new int[]{0}), // works if I leave out the new int[]{0}
};
private static Buff[] availableBuffs = new Buff[]{
new TestBuff(2f, "TestBuff was applied")
};
public static Weapon CreateWeapon(int index){
return new Weapon(availableWeapons[index]); //Works perfectly
}
public static Buff CreateBuff(int index){
Debug.Log("Trying to create a buff with index "+ index); // >>Trying to create a buff with index 0
if(availableBuffs[index] == null) Debug.Log("But it is null"); // Already thows an exeption
return new Buff(availableBuffs[index]); //Throws an exeption
}
}
The constructors for the weapon class:
public Weapon(Weapon wp ){
//some stuff
this.myBuffs = wp.MyBuffs;
}
public Weapon( /* some stuff*/ ,int[] newBuffs = null){
//some stuff
if(myBuffs != null) myBuffs.Clear();
else myBuffs = new List<Buff>();
if(newBuffs != null)
foreach(int i in newBuffs)
myBuffs.Add(WeaponList.CreateBuff(i)); // works if I replace it with myBuffs.Add(new TestBuff(new TestBuff(2f,"some string")));
}
The constructors for the Buff classes:
public class Buff {
//stuff
public Buff(Buff referenceBuff){
this.duration = referenceBuff.Duration;
}
public Buff(float dura){
duration = dura;
}
}
public class TestBuff : Buff{
//stuff
public TestBuff(TestBuff newBuff) : base(newBuff){
this.myMessage = newBuff.MyMessage;
}
public TestBuff(float dura, string message) : base(dura){
myMessage = message;
}
}