
php artisan serve 
Scripts folder using the Create -> C# Script command on the Project panel. Let's call it WWWScore and open the resulting WWWScore.cs file in your Unity editor ( Visual Studio , MonoDevelop ).[SerializeField] in order to be able to change this private variable through the Inspector panel in Unity . [SerializeField] private string serverURL = "http://127.0.0.1:8000/"; public IEnumerator AddRecord(int score) { WWWForm form = new WWWForm(); form.AddField("score", score); WWW w = new WWW(serverURL + "api/anonymrecord", form); yield return w; if(!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { Debug.Log(" !"); } } score variable, which we will transmit when calling the coroutine from the GameController class), form a request at http://127.0.0.1:8000/api/anonymrecord and wait for the result. As soon as a response comes from the server (or expires the request timeout), the Record Added! Message will be displayed in the console ! , or error information in case of failure.WWWScore.cs script to the Game Controller object via the Add Component button on the Inspector panel, or simply by dragging the script with the mouse on the object.
GameController.cs script, adding the coroutine call there. void Update () { if (gameover){ // , if (!gameoverStarted) { gameoverStarted = true; // restartText.SetActive(true); // // StartCoroutine(GetComponent<WWWScore>().AddRecord(score)); } // ... } else { // ... } // ... } 

Login(string email, string password) authorization function Login(string email, string password) to WWWScore.cs , which we will later transmit to the coroutine. Similar to the function of adding records, it forms a POST request to our site on Laravel , passing the data set to it at http://127.0.0.1:8000/oauth/token . We considered the necessary data for authorization in the first part of the article. WWWForm form = new WWWForm(); form.AddField("grant_type", "password"); form.AddField("client_id", "<Client ID>"); form.AddField("client_secret", "<Client Secret>"); form.AddField("username", email); // form.AddField("password", password); // form.AddField("scope", "*"); json . This can be done using the JsonUtility by converting json to an object. We describe the class of the object in the same WWWScore.cs file before describing the WWWScore class. [Serializable] public class TokenResponse { public string access_token; } json object there will be 4 fields, but we only need the access_token field, which we describe in the class. Now you can add the json conversion to the object itself. TokenResponse tokenResponse = JsonUtility.FromJson<TokenResponse>(w.text); PlayerPrefs.SetString("Token", tokenResponse.access_token); StartCoroutine(GetUserInfo()); [Serializable] public class TokenResponse { public string access_token; } public class WWWScore : MonoBehaviour { // ... public IEnumerator Login(string email, string password) { WWWForm form = new WWWForm(); form.AddField("grant_type", "password"); form.AddField("client_id", "3"); form.AddField("client_secret", "W82LfjDg4DpN2gWlg8Y7eNIUrxkOcyPpA3BM0g3s"); form.AddField("username", email); form.AddField("password", password); form.AddField("scope", "*"); WWW w = new WWW(serverURL + "oauth/token", form); yield return w; if (!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { TokenResponse tokenResponse = JsonUtility.FromJson<TokenResponse>(w.text); if (tokenResponse == null) { Debug.Log(" !"); } else { // PlayerPrefs.SetString("Token", tokenResponse.access_token); Debug.Log(" !"); // StartCoroutine(GetUserInfo()); } } } } null ). Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("Authorization", "Bearer " + PlayerPrefs.GetString("Token")); WWW w = new WWW(serverURL + "api/user", null, headers); json , for parsing which we need to create a separate class with the only field we need from the whole json structure - the name. [Serializable] public class UserInfo { public string name; } UserInfo userInfo = JsonUtility.FromJson<UserInfo>(w.text); PlayerPrefs.SetString("UserName", userInfo.name); // TokenResponse // ... [Serializable] public class UserInfo { public string name; } public class WWWScore : MonoBehaviour { // ... // Login // ... public IEnumerator GetUserInfo() { Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("Authorization", "Bearer " + PlayerPrefs.GetString("Token")); WWW w = new WWW(serverURL + "api/user", null, headers); yield return w; if (!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { UserInfo userInfo = JsonUtility.FromJson<UserInfo>(w.text); if (userInfo == null) { Debug.Log(" !"); } else { // PlayerPrefs.SetString("UserName", userInfo.name); Debug.Log(" !"); } } } } AddRecord(int score) . Add a check if the authorization token is filled in the settings, and if so, we will add it to the Headers in the same way as when receiving information about the user, with the only difference that we are still passing the record in the POST request data. WWW w; if (PlayerPrefs.HasKey("Token")) { Dictionary<string, string> headers = new Dictionary<string, string>(); byte[] rawData = form.data; headers.Add("Authorization", "Bearer " + PlayerPrefs.GetString("Token")); w = new WWW(serverURL + "api/record", rawData, headers); } else { w = new WWW(serverURL + "api/anonymrecord", form); } public IEnumerator AddRecord(int score) { WWWForm form = new WWWForm(); form.AddField("score", score); WWW w; if (PlayerPrefs.HasKey("Token")) { Dictionary<string, string> headers = new Dictionary<string, string>(); byte[] rawData = form.data; headers.Add("Authorization", "Bearer " + PlayerPrefs.GetString("Token")); w = new WWW(serverURL + "api/record", rawData, headers); } else { w = new WWW(serverURL + "api/anonymrecord", form); } yield return w; if(!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { Debug.Log(" !"); } } public void Logout() { PlayerPrefs.DeleteAll(); } GameController.cs ) to work with user authorization. We will need objects with the loginObj authorization loginObj and the logoutObj exit panel so that we can switch them. On the authorization panel there will be input fields for the email address ( inputFieldEmail ) and for the password ( inputFieldPassword ). We will also need the text userNameText to display the name of the user who logged in to your account. // public GameObject loginObj; // public GameObject logoutObj; // E-mail public GameObject inputFieldEmail; // public GameObject inputFieldPassword; // public GameObject userNameText; Login() function, which will be called by clicking on the Login button, read the email address with a password and call the coroutine with the same function from WWWScore.cs . public void Login() { var email = inputFieldEmail.GetComponent<InputField>().text; var password = inputFieldPassword.GetComponent<InputField>().text; StartCoroutine(GetComponent<WWWScore>().Login(email, password)); } WWWScore.cs without any parameters. public void Logout() { GetComponent<WWWScore>().Logout(); } public void SetLoginVisible() { if (PlayerPrefs.HasKey("Token")) { loginObj.SetActive(false); logoutObj.SetActive(true); } else { loginObj.SetActive(true); logoutObj.SetActive(false); } } public void SetUserName() { if (PlayerPrefs.HasKey("UserName")) { userNameText.GetComponent<Text>().text = PlayerPrefs.GetString("UserName"); } else { userNameText.GetComponent<Text>().text = ""; } } Update() function: void Update () { // ... // // ... SetUserName(); SetLoginVisible(); } Pause socket attached to the Canvas object. Create a new empty object ( Create Empty ), call it Login and put it inside the Pause panel, on the same level as the Title (the inscription Pause ). Add to it the component Graphic Raycaster (for correct work with nested elements).
Login object we will add two input fields, InputFieldEmail and InputFieldPassword ( UI -> Input Field ), changing the placeholder text for clarity. For the Input Field component, in the InputFieldEmail object InputFieldEmail we change the data type in the Content Type field to Email Address , and in the InputFieldPassword object, to Password . Add a ButtonLogin button ( UI -> Button ) to the same Login object. The interface will look something like this (if you play around with the fonts and the size of the components).
ButtonLogin button. On the Button component on the Inspector panel, click on the plus sign on the On Click () event, select Editor and Runtime from the list (to work correctly during the debugging process) and drag the Game Controller object there (with the mouse or by selecting it when clicking on the selection circle at the object field ). In the pop-up menu that appears after this, select the GameController component and the Login() function in it.
Login object — its display is adjusted in GameController.cs .Logout object similar to the Login object (without forgetting the Graphic Raycaster component) nested in Pause . Add only the ButtonLogout button to the Logout object. Similar to the previous button, we will bind the GameController component's GameController same name to the click event of the click.
Logout object and the Pause panel itself.User element ( UI -> Text ) to the main Canvas before the Pause element, GameController.cs Anonymous in it (or leave it empty, since the inscription will be assigned in GameController.cs ) and placed in the upper right corner. The name of the authorized user will be displayed here.
GameController object. On the Inspector panel, the Game Controller component has several empty fields that we added in the code earlier. Assign the corresponding objects to them by dragging with the mouse from the Hierarchy panel or selecting from the list after clicking on the selection circle near the field.




using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [Serializable] public class TokenResponse { public string access_token; } [Serializable] public class UserInfo { public string name; } public class WWWScore : MonoBehaviour { [SerializeField] private string serverURL = "http://127.0.0.1:8000/"; public IEnumerator AddRecord(int score) { WWWForm form = new WWWForm(); form.AddField("score", score); WWW w; if (PlayerPrefs.HasKey("Token")) { Dictionary<string, string> headers = new Dictionary<string, string>(); byte[] rawData = form.data; headers.Add("Authorization", "Bearer " + PlayerPrefs.GetString("Token")); w = new WWW(serverURL + "api/record", rawData, headers); } else { w = new WWW(serverURL + "api/anonymrecord", form); } yield return w; if(!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { Debug.Log(" !"); } } public IEnumerator Login(string email, string password) { WWWForm form = new WWWForm(); form.AddField("grant_type", "password"); form.AddField("client_id", "3"); // form.AddField("client_secret", "W82LfjDg4DpN2gWlg8Y7eNIUrxkOcyPpA3BM0g3s"); // form.AddField("username", email); form.AddField("password", password); form.AddField("scope", "*"); WWW w = new WWW(serverURL + "oauth/token", form); yield return w; if (!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { TokenResponse tokenResponse = JsonUtility.FromJson<TokenResponse>(w.text); if (tokenResponse == null) { Debug.Log(" !"); } else { // PlayerPrefs.SetString("Token", tokenResponse.access_token); Debug.Log(" !"); // StartCoroutine(GetUserInfo()); } } } public IEnumerator GetUserInfo() { Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("Authorization", "Bearer " + PlayerPrefs.GetString("Token")); WWW w = new WWW(serverURL + "api/user", null, headers); yield return w; if (!string.IsNullOrEmpty(w.error)) { Debug.Log(w.error); } else { UserInfo userInfo = JsonUtility.FromJson<UserInfo>(w.text); if (userInfo == null) { Debug.Log(" !"); } else { // PlayerPrefs.SetString("UserName", userInfo.name); Debug.Log(" !"); } } } public void Logout() { PlayerPrefs.DeleteAll(); } } using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; // [System.Serializable] public class PanClass { // public GameObject panObj; // public float start; // public float pause; } public class GameController : MonoBehaviour { // public PanClass pan; // public Vector2 spawnValues; // public GameObject scoreText; // public GameObject restartText; // public GameObject pausePanel; // public float scoreRate = 1.0F; // , public int scoreAdd = 10; // public static int score; // public static bool gameover; // private float nextScore = 0.0F; // , private bool gameoverStarted; // public GameObject loginObj; // public GameObject logoutObj; // E-mail public GameObject inputFieldEmail; // public GameObject inputFieldPassword; // public GameObject userNameText; void Start () { // ( ) gameover = false; score = 0; gameoverStarted = false; // StartCoroutine(PanSpawn()); } void FixedUpdate() { if (!gameover) { // scoreText.GetComponent<Text>().text = score.ToString(); } } void Update () { if (gameover){ // , if (!gameoverStarted) { gameoverStarted = true; // restartText.SetActive(true); // StartCoroutine(GetComponent<WWWScore>().AddRecord(score)); } // R if (Input.GetKey(KeyCode.R)) { // SceneManager.LoadScene(0); } } else { if (Input.GetKeyDown(KeyCode.Escape)) { if (Time.timeScale != 0) { // Time.timeScale = 0; pausePanel.SetActive(true); } else { // Time.timeScale = 1; pausePanel.SetActive(false); } } } // if (!gameover && (Time.time > nextScore)) { nextScore = Time.time + scoreRate; score = score + scoreAdd; } SetUserName(); SetLoginVisible(); } // IEnumerator PanSpawn() { // yield return new WaitForSeconds(pan.start); // , while (!gameover) { // Vector2 spawnPosition = new Vector2(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y); Quaternion spawnRotation = Quaternion.identity; Instantiate(pan.panObj, spawnPosition, spawnRotation); yield return new WaitForSeconds(pan.pause); } } // public void Login() { var email = inputFieldEmail.GetComponent<InputField>().text; var password = inputFieldPassword.GetComponent<InputField>().text; StartCoroutine(GetComponent<WWWScore>().Login(email, password)); } // public void Logout() { GetComponent<WWWScore>().Logout(); } // public void SetLoginVisible() { if (PlayerPrefs.HasKey("Token")) { loginObj.SetActive(false); logoutObj.SetActive(true); } else { loginObj.SetActive(true); logoutObj.SetActive(false); } } // public void SetUserName() { if (PlayerPrefs.HasKey("UserName")) { userNameText.GetComponent<Text>().text = PlayerPrefs.GetString("UserName"); } else { userNameText.GetComponent<Text>().text = ""; } } } master branch)final branch)Source: https://habr.com/ru/post/340362/
All Articles