No matter what i change the parameters to, Instantiate() throws a NullReferenceException, even after it successfully instantiates the GameObject.
I've used Debug.Log on all the parameters to check if any of them are null, they aren't
Yet still, the Instantiate function throws a NullReferenceException
All of this is based on the assumption that the reason its throwing a NullReferenceException is because one of the parameters is null, but clearly something else is wrong. How do I fix this?
The full code looks like this:
public class BattleSystem : MonoBehaviour
{
public static Unit selected;
public BattleState battleState;
public GameState gameState;
public GameObject baseUnit;
public Vector2 playerPos, enemyPos;
public Vector2 posOffset;
public List<Effect> statusEffects = new();
//-----------This is placeholder code----------
public List<Unit> allyTeamUnits, enemyTeamUnits = new(3);
//----Remember to add a loading mechanic------
List<GameObject> playerTeamUnitsGO, enemyTeamUnitsGO;
public GameObject canvas;
private void Awake()
{
gameState = GameState.starting;
SetupBattle();
}
IEnumerator Start()
{
yield return new WaitForSeconds(2f);
battleState = BattleState.playerPassive;
}
void SetupBattle() //should be called at the start of the battle
{
Debug.Log("setup battle is called");
for (int i = 0; i < allyTeamUnits.Count; i++)
{
Debug.Log(baseUnit == null);
Debug.Log(playerPos == null);
Debug.Log(Quaternion.identity == null);
Debug.Log(canvas.transform == null);
playerTeamUnitsGO[i] = Instantiate(baseUnit, playerPos, Quaternion.identity, canvas.transform); //This line throws NullReferenceException
playerTeamUnitsGO[i].SetActive(true);
playerTeamUnitsGO[i].GetComponent<Unit>().Init(allyTeamUnits[i]);
}
Debug.Log("info initialized");
for (int i = 0; i < enemyTeamUnits.Count || i < 3; i++)
{
enemyTeamUnitsGO[i] = Instantiate(baseUnit, enemyPos, Quaternion.identity, canvas.transform); //spawning an enemy
enemyTeamUnitsGO[i].SetActive(true);
enemyTeamUnitsGO[i].GetComponent<Unit>().Init(enemyTeamUnits[i]);
}
}
}
baseUnit has a GameObject attached to it. After the Instantiate(), nothing after the exception runs. I've also tried changing the GameObject to a dummy one, but that didn't work either, and it still throws the exception.