1

I have an array InputFields, in my situation - six InputFields. How can I get the text and save it from each InputField?

Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.

I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.

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

public class SaveText : MonoBehaviour {
    public GameObject[] InputFields;
    public static string n;

    public void Start ()
{
    for(int i = 0; i < InputFields.Length; i++)
    {
        InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
        Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
        n = InputFields[i].name;
        var input = InputFields[i].GetComponent<InputField> ();
        var se = new InputField.SubmitEvent ();
        se.AddListener (SubmitName);
        input.onEndEdit = se;
    }

}

public void SubmitName(string arg)
{
    PlayerPrefs.SetString (n, arg);
}

An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.

halfer
  • 19,824
  • 17
  • 99
  • 186
Roma Sypko
  • 53
  • 1
  • 5
  • 1
    What's exactly the problem? You already have the fields inside the array InputFields. If press submitName, you have to loop through and collect the content out of each box. Wouldn't be bad to create an object containing an attribute for each textfield you are going to access – Alex Cio Jan 21 '17 at 14:22
  • @AlexCio The problem is that I want to when I changed the value in the input fields, and then switched to another scene, or shuts down the application, those values which I have entered, they are displayed in these fields for the input to the next edit. How can I implement this? – Roma Sypko Jan 21 '17 at 14:36
  • I hope I understood correctly what you wanted to say. Try the methods in my post and it should work! – Alex Cio Jan 21 '17 at 15:53

2 Answers2

0

Well, you are using a single variable for all the different player prefs variables, n. So when you change a field (with SubmitName) it uses that n pref variable and changes it. This will correspond to the last value you gave to n in your loop.

An option would be to have that be an array too (private string prefValues[]) or to pass the calling input field to SubmitName (or rather it's name) and use that instead of n.

A little example (from your code you can actually change your GameObject[] to InputField[] which saves some GetComponent calls):

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

public class EventTest : MonoBehaviour
{
    public InputField[] inputFields;

    void Start ()
    {
        foreach(InputField field in inputFields)
        {
            var se = new InputField.SubmitEvent();
            se.AddListener(delegate {
                SubmitText(field.name, field.text);
            });
            field.onEndEdit = se;
        }
    }

    public void SubmitText(string prefKey, string prefVal)
    {
        Debug.Log("Saved " + prefVal + " to " + prefKey);
    }
}

Edit:
Added lines for saving/loading from prefs in the code below. For my test setup I just have two scenes. Both have two input fields and a button that calls that scene change. I can type stuff on the fields as I like, change scenes and it stays. Also upon restarting playmode in the editor.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class EventTest : MonoBehaviour
{
    public InputField[] inputFields;

    void Start ()
    {
        foreach(InputField field in inputFields)
        {
            // Get field values from player prefs if existing
            // (it should only not exist the very first time or if you delete/clear the prefs)
            if(PlayerPrefs.HasKey(field.name))
                field.text = PlayerPrefs.GetString(field.name);

            var se = new InputField.SubmitEvent();
            se.AddListener(delegate {
                SubmitText(field.name, field.text);
            });
            field.onEndEdit = se;
        }
    }

    public void SubmitText(string prefKey, string prefValue)
    {
        // store the typed text of the respective input field
        PlayerPrefs.SetString(prefKey, prefValue);
    }

    public void ChangeScene()
    {
        if(SceneManager.GetActiveScene().name == "Scene1")
        {
            SceneManager.LoadScene("Scene2");
        }
        else
        {
            SceneManager.LoadScene("Scene1");
        }
    }
}
Gunnar B.
  • 2,879
  • 2
  • 11
  • 17
  • Your code is written right, thank you very much! But this gives me the opportunity to bring in a console that I kept in the input field, and I want to be able to save the text in this field until his next editing. I try to do this using the "PlayerPrefs". Below I have posted the code, but this code does not work for some reason. Help me please) `public void SubmitText(string prefValue, string val) { //Debug.Log("Saved " + val + " to " + prefValue); PlayerPrefs.SetString (prefValue, val); }` – Roma Sypko Jan 21 '17 at 20:12
  • As I understand it, the PlayerPrefs takes two arguments - key and value, as I understand your code, then prefValue is the key, and the val - value. – Roma Sypko Jan 21 '17 at 20:14
  • Yes, `prefValue` is meant as the key. How does your code not work? Doesn't it save the string to the player prefs? – Gunnar B. Jan 21 '17 at 20:34
  • Yes,unfortunately the code is not working properly. It does not save the string to the PlayerPrefs. I dont know why...I'll tell you, as of now the program works: I run the app, input fields are empty, I write in the input fields any values, for example, in the first field - word one, word two in the second field, etc. Each entry I press enter. After entering all the values I move to another scene or turn off the application, and run again. But in the input fields empty :( In your code, I just added the following line: PlayerPrefs.SetString (prefKey, prefVal); – Roma Sypko Jan 22 '17 at 09:16
  • You did add the `GetString` part too? My code in `Start` only does the listener with the delegate. – Gunnar B. Jan 22 '17 at 11:28
  • Let me explain what I want. `Actual result:` [link](http://g.recordit.co/89BdFC00qT.gif) I enter values, move on to another scene, and returns back to the stage where I entered values. `Expected result:` I want to value that I wrote in the input fields saves in PlayerPrefs and then the program reads the values in PlayerPrefs and displays them in the input fields again. – Roma Sypko Jan 24 '17 at 18:22
  • As said, the code works **if** you have the `GetString` part which my first code did not have. I added a second code that works perfectly fine (read description). – Gunnar B. Jan 24 '17 at 21:25
0

If you want to save the data, after the application stopped or if it gets paused, you need to add some more functions to your MonoBehavior so that it can handle additional actions on a system end or pause.

Look at following functions in the documentation

OnApplicationQuit()

OnApplicationPause()

These functions will be called automatically. Inside these functions you need to iterate through the textfields and save them. It is one of the last functions that will be called before the program will lose it's recourses.

Regarding the Scene change, you would need the new scene to tell the old one to do any further actions. Like you can read in this post, there is only a way to know if a new scene was loaded. Maybe you have a place where you can save the last active scene object and then call the last scenes function to do the saving process while the object is not cleared.

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
  • This will not help for scene translation etc. and is not needed if he uses player prefs in the event listener since that changes (and saves) it immediatly. – Gunnar B. Jan 21 '17 at 16:23
  • I updated my answer, but I think you need to create a custom why to achieve what you want. – Alex Cio Jan 21 '17 at 19:04