I'm working on learning how pass data from one script to the other in Unity and I'm getting a little confused. I have two scripts, PlayerData
and CreateCharacter
. PlayerData
is used to pass persistent data from one scene to another, so it's not going to be attached to any GameObject
or Transform
. CreateCharacter
, however, is attached to a button which gets the information from user input. Here are the two scripts:
PlayerData
public class PlayerData{
private string playerName;
public string PlayerName{
get{return playerName;}
set{playerName = value;}
}
}
CreateCharacter
public class CreateCharacter:MonoBehaviour{
public InputField playerName;
public PlayerData playerData = new PlayerData();
public void AddStats(){}
public void SubtractStats(){}
public void CreateCharacterOnClick(){
playerData.PlayerName = playerName.text;
Debug.Log(playerData.PlayerName);
}
}
What's happening is, when I click the button I'm getting a null reference error on playerData.PlayerName
but if I just log playerData
I actually get the object to return. What I'm trying to see is that the character name(playerName
) is logged when the button is clicked. Can anyone explain to me what I'm doing wrong and how to fix it?