How to pass a string between scenes and display it?

I’m trying to take in the player name using an InputField then I want to display it on the next scene.


I’ve tried numerous times using the code listed below and other methods but an unassigned reference exception seems to be preventing my success.

Can someone provide an alternative solution that can allow me to pass the Input field information to the next scene and display it?

Input Player Name

using UnityEngine;
using UnityEngine.UI;

public class nameSelection : MonoBehaviour
{
    public static nameSelection askName;
    public InputField inputField;
    public string userName;


    private void Awake()
    {
        if (askName == null)
        {
            askName = this;
            DontDestroyOnLoad(gameObject);
        }
        else Destroy(gameObject);
    }

    private void Update()
    {
        if (userName != inputField.text)
        {
            userName = inputField.text;
        }
    }
}

Display Player Name on Next Scene

using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class GetName : MonoBehaviour
{
    public GameObject textDisplay;

    public void Awake()
    {
        textDisplay.GetComponent<Text>().text = nameSelection.askName.userName + "'s Score";
    }
}

Thank You

1 Like

I would not do it this way. You don’t need to keep around the entire monobehavior just to pass a string around. Make yourself a static class and use that for all exchanges of data between the scenes. The only monobehaviors you want to keep around like this are ones that do something in both scenes (like playing music uninterrupted between scenes).

That said, I think why you’re getting the error is simply because you have the behavior updating constantly, and the thing it is updating with is another object which is destroyed. So the update routine needs a change to prevent it from updating all the time, and should only update while that other object is available. Again, probably better to use an independent static class and whatever triggers a scene change should just grab the text at that point, set the variable in the static class just the once, then switch scenes. No need to grab the value every frame update.

There should not be any need to keep updating and check input field, it has its own callback when editing and end of editing that you can use.

Also the reason you get an error is most likely because you are extending(using?) monobehaviour

The way I usualy deal with data that are needed between scene is to make a scriptable object that can contains the values you need then just call it between scene since they do not get cleared when switching scenes.