Login.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 (result.Equals("Success")) {
  64. errorColor.a = 0;
  65. errorText.color = errorColor;
  66. // load next scene
  67. SceneManager.LoadScene("MainMenu");
  68. } else {
  69. errorText.text = "Misslyckades med inloggning";
  70. errorColor.a = 1;
  71. errorText.color = errorColor;
  72. }
  73. }
  74. }