I'm making a save system for my game, and have run into a NullReferenceException while loading the keybindings for one of the player objects (player 2). Since I used identical code to load the keybinds for player 1, and that one works fine, I believe that the problem comes from player 2 being inactive when the load script is run.
Here's most of the relevant code, based on Brackey's Save/Load tutorial:
public string[] player1;
public string[] player2;
public GameData(AchievementsManager am, GameObject play2)
{
var p1 = play1.GetComponent<playerMovement>();
var p2 = play2.GetComponent<playerMovement>();
player1 = new string[4] { p1.up, p1.down, p1.left, p1.right};
player2 = new string[4] { p2.up, p2.down, p2.left, p2.right};
}
public class SaveManager : MonoBehaviour
{
public GameObject play2;
void Start()
{
GameData data = SaveSystem.loadGame();
if (data != null)
{
var p1 = play1.GetComponent<playerMovement>();
var p2 = play2.GetComponent<playerMovement>();
string[] p1_controls = data.player1;
string[] p2_controls = data.player2;
p1.up = p1_controls[0]; p2.up = p2_controls[0];
p1.down = p1_controls[1]; p2.down = p2_controls[1];
p1.left = p1_controls[2]; p2.left = p2_controls[2];
p1.right = p1_controls[3]; p2.right = p2_controls[3];
}
}
}
The error is on the line p2.up = p2_controls[0];, but I think that it's because there's a problem with play2.GetComponent<playerMovement>(); related to player 2 being inactive at startup. Is there a good way to fix this without making player 2 active at startup, or at least a way to better understand what exactly is causing the problem?
play2 is a GameObject referenced in the class header of SaveManager. play2 does have a playerMovement component that runs properly. I think that the NullReferenceException comes from the SaveManager not properly loading the information that it contains.
play2does not have aplayerMovementcomponent attached to it and soGetComponentis returningnull. There is not enough information in the question to understand why that might be. Can't help any more than that without more information in the question.loadGamecallsGameData(AchievementsManager am, GameObject play2)somewhere. An explanation of whereplay2comes from would be a good start :p