简体   繁体   中英

Using Unity5 and C# get strings from input fields and display strings in another scene

I created a game object that has dont destroy on load. I want this to be the holder for the input data so that I can access the strings in another scene. The problem is how to get the user input from the input text fields into my game object and back into a text field in another scene. I am thinking that I may use the built in scripts On End Edit (string) script attached to the input fields in the inspector in order to pass the input to my game object. My goal is to get strings from user input and display it all formatted nicely in another scene. I have also tagged all of my input fields and have attached a script to my game object that finds all game objects with the tag. This may be a better way to go about getting the strings.

I'd use playerprefs to save data for another session. If you just want to save the data for another scene, use a static class. You don't even need "Dontdestroyonload"

Create this class in your project:

public static class ExampleUserData
{
    public static string MyUserData1;
    public static string MyUserData2;
    //etc..
}

Attach this class to a gameobject in your scene 1:

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class ExampleScene1 : MonoBehaviour
{
    InputField input1;
    InputField input2;

    void Awake()
    {
        //input1 = something...;
        //input2 = something...;
    }

    void LoadScene2()
    {
        ExampleUserData.MyUserData1 = input1.text;
        ExampleUserData.MyUserData2 = input2.text;

        SceneManager.LoadScene("Scene2");
    }
}

This one in your second scene:

using UnityEngine;
using UnityEngine.UI;

public class ExampleScene2 : MonoBehaviour
{
    InputField input1;
    InputField input2;

    void Awake()
    {
        //input1 = something...;
        //input2 = something...;
    }

    void Start()
    {
        input1.text = ExampleUserData.MyUserData1;
        input2.text = ExampleUserData.MyUserData2;
    }
}

Replace the code in the Awake() to find your input fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM