Login.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. using UnityEngine.UI;
  6. using UnityEngine.EventSystems;
  7. using UnityEngine.SceneManagement;
  8. public class Login : MonoBehaviour {
  9. public GameObject username;
  10. public GameObject password;
  11. public Button loginButton;
  12. public Text errorText;
  13. private string Username;
  14. private string Password;
  15. private string loginUrl = "http://nordh.xyz/narKampen/dbFiles/Login.php?";
  16. private Color errorColor;
  17. private EventSystem system;
  18. private void Start() {
  19. loginButton.onClick.AddListener(loginAction);
  20. errorColor = errorText.color;
  21. system = EventSystem.current;
  22. }
  23. private void Update() {
  24. Username = username.GetComponent<InputField>().text;
  25. Password = password.GetComponent<InputField>().text;
  26. if (Input.GetKeyDown(KeyCode.Tab)) {
  27. Selectable next = system.currentSelectedGameObject.GetComponent<Selectable>().FindSelectableOnDown();
  28. if (next != null) {
  29. InputField inputfield = next.GetComponent<InputField>();
  30. if (inputfield != null) inputfield.OnPointerClick(new PointerEventData(system)); //if it's an input field, also set the text caret
  31. system.SetSelectedGameObject(next.gameObject, new BaseEventData(system));
  32. }
  33. }
  34. }
  35. void loginAction() {
  36. string errorMessage = "";
  37. if (Username == "") {
  38. errorMessage = "Username is required";
  39. }
  40. if (Password == "") {
  41. if (errorMessage != "") {
  42. errorMessage += "\n";
  43. }
  44. errorMessage += "Password is required";
  45. }
  46. if (errorMessage == "") {
  47. errorColor.a = 0;
  48. StartCoroutine(loginCall());
  49. } else {
  50. errorText.text = errorMessage;
  51. errorColor.a = 1;
  52. }
  53. errorText.color = errorColor;
  54. }
  55. IEnumerator loginCall() {
  56. string postUrl = loginUrl + "name=" + UnityWebRequest.EscapeURL(Username) + "&password=" + UnityWebRequest.EscapeURL(Password);
  57. UnityWebRequest www = UnityWebRequest.Get(postUrl);
  58. yield return www.SendWebRequest();
  59. if (www.error != null) {
  60. errorText.text = "There was an error logging in " + www.error;
  61. }
  62. string result = www.downloadHandler.text;
  63. if (int.TryParse(www.downloadHandler.text, out int userId)) {
  64. errorColor.a = 0;
  65. errorText.color = errorColor;
  66. PlayerPrefs.SetInt("UserId", userId);
  67. // load next scene
  68. SceneManager.LoadScene("MainMenu");
  69. } else {
  70. errorText.text = "Misslyckades med inloggning";
  71. errorColor.a = 1;
  72. errorText.color = errorColor;
  73. }
  74. }
  75. }