I have been trying to work out a subscription form for my game and thanks to you guys here, I came to a solution which works but still needs some changes.
The idea is to have an input field in the scene that takes the users email and convert it into JSON (to do a POST request). I have made the post request and everything works fine but I have to manually type the email in the inspector. What I would want is to get that value from the input field!
public class testing : MonoBehaviour
{
public TMP_InputField myField;
//public InputField field;
[SerializeField]
private Email _email = new Email();
private string URL = "";
public void SaveData()
{
string data = JsonUtility.ToJson(_email); // this part here needs to be like _email.text
System.IO.File.WriteAllText(Application.persistentDataPath + "Data.json", data);
StartCoroutine(SaveIntoJson(URL , data));
}
IEnumerator SaveIntoJson(string url, string data)
{
var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
request.SetRequestHeader("Content-Type", "application/json");
var jsonBytes = Encoding.UTF8.GetBytes(data);
request.uploadHandler = new UploadHandlerRaw(jsonBytes);
request.downloadHandler = new DownloadHandlerBuffer();
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
Debug.Log(request.downloadHandler.text);
}
else
{
Debug.Log("Form upload complete!");
}
Debug.Log(data);
}
}
[System.Serializable]
public class Email
{
public List<Profiles> profiles = new List<Profiles>();
}
[System.Serializable]
public class Profiles
{
[SerializeField]
public string email; // this part here works but i need to type the email in the inspector
}
also the requirements for the json are like this
{"profiles":[{"email":"[email protected]"}]}
public void SaveData() { Profiles profile = new Profiles(); profile.email = field.text; string data = JsonUtility.ToJson(profile); System.IO.File.WriteAllText(Application.persistentDataPath + "Data.json", data); StartCoroutine(SaveIntoJson(URL , data)); }
\$\endgroup\$