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:


public class PlayerData{
    private string playerName;

    public string PlayerName{
        get{return playerName;}
        set{playerName = value;}


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;

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?


2 Answers 2


As I understand it, you get a null reference exception here:

playerData.PlayerName = playerName.text;

You seem to think it's because of playerData, but I don't think that's the case. You initialize playerData (public PlayerData playerData = new PlayerData();, above).

What you don't initialize... at least in the code you've posted here... is playerName. You declare it above (public InputField playerName;) but you don't assign it a new instance.

Unless you are initializing playerName elsewhere, then you try to read the text from that input field you will get a null reference exception, because it's null. That's probably why if you remove that and "just log playerData" you get sane results.

I'd suggest you initialize the input field somewhere.


Your problem is that you're never initializing the playerName property in PlayerData. By default, that particular string is going to be null, while the playerData object is not, hence why the log works.

All you have to do is give a value to playerName in playerData.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .