0
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.