chunk 1: core gameplay scripts scenes runtime assets
This commit is contained in:
215
Assets/Scripts/Aunthetication/UserLogin.cs
Normal file
215
Assets/Scripts/Aunthetication/UserLogin.cs
Normal file
@@ -0,0 +1,215 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
using TMPro;
|
||||
using UnityEngine.SceneManagement;
|
||||
using UnityEngine.EventSystems;
|
||||
|
||||
// UserLogin: Clean single class implementation.
|
||||
// Features: email/password login, guest panel (show/accept/decline), guest login, menu transition, click SFX.
|
||||
public class UserLogin : MonoBehaviour
|
||||
{
|
||||
[Header("Credentials UI")] public TMP_InputField emailInput;
|
||||
public TMP_InputField passwordInput;
|
||||
public TextMeshProUGUI feedbackText;
|
||||
public GameObject loadingIndicator;
|
||||
|
||||
[Header("Guest Flow UI")] public GameObject guestPanel; // Confirmation panel
|
||||
public GameObject loginLandingPanel; // Landing buttons/panel (should stay visible behind guest panel)
|
||||
[Header("Guest Flow Buttons (Optional Auto-Wire)")]
|
||||
public UnityEngine.UI.Button guestButton;
|
||||
public UnityEngine.UI.Button guestAcceptButton;
|
||||
public UnityEngine.UI.Button guestDeclineButton;
|
||||
|
||||
[Header("Audio (Optional)")] public AudioClip clickSfx;
|
||||
private AudioSource uiAudio;
|
||||
|
||||
private const string MenuSceneName = "MenuScene";
|
||||
private const string AuthTokenKey = "AuthToken";
|
||||
[SerializeField] private string loginUrl = "http://127.0.0.1:8001/auth/token/login/";
|
||||
|
||||
private GameInitialize gameInitialize;
|
||||
private string authToken;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
gameInitialize = GameInitialize.Instance;
|
||||
if (!gameInitialize) Debug.LogError("[UserLogin] GameInitialize not found.");
|
||||
|
||||
if (!guestPanel) guestPanel = GameObject.Find("GuestPanel");
|
||||
if (!loginLandingPanel) loginLandingPanel = GameObject.Find("Login Landing Panel");
|
||||
|
||||
// Auto-wire buttons (by name) if not assigned explicitly
|
||||
if (!guestButton)
|
||||
{
|
||||
var go = GameObject.Find("GuestButton");
|
||||
if (go) guestButton = go.GetComponent<UnityEngine.UI.Button>();
|
||||
}
|
||||
if (!guestAcceptButton)
|
||||
{
|
||||
var go = GameObject.Find("Accept");
|
||||
if (go) guestAcceptButton = go.GetComponent<UnityEngine.UI.Button>();
|
||||
}
|
||||
if (!guestDeclineButton)
|
||||
{
|
||||
var go = GameObject.Find("Decline");
|
||||
if (go) guestDeclineButton = go.GetComponent<UnityEngine.UI.Button>();
|
||||
}
|
||||
|
||||
if (guestButton)
|
||||
{
|
||||
guestButton.onClick.RemoveListener(ShowGuestPanel);
|
||||
guestButton.onClick.AddListener(ShowGuestPanel);
|
||||
}
|
||||
if (guestAcceptButton)
|
||||
{
|
||||
guestAcceptButton.onClick.RemoveListener(GuestAccept);
|
||||
guestAcceptButton.onClick.AddListener(GuestAccept);
|
||||
}
|
||||
if (guestDeclineButton)
|
||||
{
|
||||
guestDeclineButton.onClick.RemoveListener(GuestDecline);
|
||||
guestDeclineButton.onClick.AddListener(GuestDecline);
|
||||
}
|
||||
|
||||
uiAudio = GetComponent<AudioSource>();
|
||||
if (!uiAudio) { uiAudio = gameObject.AddComponent<AudioSource>(); uiAudio.playOnAwake = false; }
|
||||
|
||||
if (!EventSystem.current) Debug.LogWarning("[UserLogin] No EventSystem present – UI buttons won't work.");
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (guestPanel && guestPanel.activeSelf) guestPanel.SetActive(false);
|
||||
if (loginLandingPanel && !loginLandingPanel.activeSelf) loginLandingPanel.SetActive(true);
|
||||
Debug.Log($"[UserLogin] Button wiring -> Guest:{(guestButton?"OK":"MISSING")} Accept:{(guestAcceptButton?"OK":"MISSING")} Decline:{(guestDeclineButton?"OK":"MISSING")}");
|
||||
}
|
||||
|
||||
// ===== Standard Login =====
|
||||
public void LoginUser()
|
||||
{
|
||||
PlayClick();
|
||||
if (!emailInput || !passwordInput) { Debug.LogError("[UserLogin] Input fields missing."); return; }
|
||||
string email = emailInput.text; string password = passwordInput.text;
|
||||
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) { SetFeedback("Email and password are required!"); return; }
|
||||
StartCoroutine(LoginCoroutine(email, password));
|
||||
}
|
||||
|
||||
IEnumerator LoginCoroutine(string email, string password)
|
||||
{
|
||||
ShowLoadingIndicator(true);
|
||||
var payload = new LoginRequest { email = email, password = password };
|
||||
string json = JsonUtility.ToJson(payload);
|
||||
using (var req = new UnityWebRequest(loginUrl, "POST"))
|
||||
{
|
||||
req.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(json));
|
||||
req.downloadHandler = new DownloadHandlerBuffer();
|
||||
req.SetRequestHeader("Content-Type", "application/json");
|
||||
yield return req.SendWebRequest();
|
||||
|
||||
if (req.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
bool ok = false; AuthResponse resp = null;
|
||||
try { resp = JsonUtility.FromJson<AuthResponse>(req.downloadHandler.text); ok = resp != null && !string.IsNullOrEmpty(resp.auth_token); }
|
||||
catch (System.Exception ex) { Debug.LogError("[UserLogin] Parse error: " + ex.Message); }
|
||||
|
||||
if (ok)
|
||||
{
|
||||
authToken = resp.auth_token;
|
||||
PlayerPrefs.SetString(AuthTokenKey, authToken); PlayerPrefs.Save();
|
||||
if (gameInitialize) gameInitialize.SetUserAuthenticated(true);
|
||||
SetFeedback("Login Successful! Redirecting...");
|
||||
yield return new WaitForSeconds(1f);
|
||||
TriggerMenuLoad();
|
||||
}
|
||||
else { SetFeedback("Unexpected response."); ShowLoadingIndicator(false); }
|
||||
}
|
||||
else
|
||||
{
|
||||
string body = req.downloadHandler.text;
|
||||
SetFeedback(string.IsNullOrEmpty(body) ? "Login Failed." : $"Login Failed: {body}");
|
||||
ShowLoadingIndicator(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Guest Panel Flow =====
|
||||
public void ShowGuestPanel()
|
||||
{
|
||||
PlayClick();
|
||||
Debug.Log("[UserLogin] ShowGuestPanel invoked");
|
||||
if (!guestPanel)
|
||||
{
|
||||
Debug.LogWarning("[UserLogin] guestPanel missing (cannot display).");
|
||||
return;
|
||||
}
|
||||
// Keep landing panel visible behind; just layer guest panel above
|
||||
if (loginLandingPanel && !loginLandingPanel.activeSelf)
|
||||
{
|
||||
loginLandingPanel.SetActive(true);
|
||||
Debug.Log("[UserLogin] Reactivating landing panel for background");
|
||||
}
|
||||
guestPanel.transform.SetAsLastSibling();
|
||||
guestPanel.SetActive(true);
|
||||
Debug.Log("[UserLogin] Guest panel active (landing stays visible)");
|
||||
}
|
||||
|
||||
public void GuestAccept()
|
||||
{
|
||||
PlayClick();
|
||||
Debug.Log("[UserLogin] GuestAccept clicked");
|
||||
LoginAsGuest();
|
||||
}
|
||||
|
||||
public void GuestDecline()
|
||||
{
|
||||
PlayClick();
|
||||
Debug.Log("[UserLogin] GuestDecline clicked -> hiding only guest panel");
|
||||
if (guestPanel) guestPanel.SetActive(false);
|
||||
if (loginLandingPanel && !loginLandingPanel.activeSelf) loginLandingPanel.SetActive(true);
|
||||
}
|
||||
|
||||
public void LoginAsGuest()
|
||||
{
|
||||
Debug.Log("[UserLogin] LoginAsGuest starting (clearing token & loading menu)");
|
||||
PlayerPrefs.DeleteKey(AuthTokenKey);
|
||||
if (gameInitialize) gameInitialize.SetUserAuthenticated(true);
|
||||
SetFeedback("Entering as guest...");
|
||||
TriggerMenuLoad();
|
||||
}
|
||||
|
||||
// ===== Helpers =====
|
||||
void TriggerMenuLoad()
|
||||
{
|
||||
ShowLoadingIndicator(true);
|
||||
Debug.Log("[UserLogin] TriggerMenuLoad invoked. Using SceneLoader -> " + MenuSceneName);
|
||||
var op = SceneLoader.LoadSceneAsyncOnce(MenuSceneName, LoadSceneMode.Single, true);
|
||||
if (op == null)
|
||||
{
|
||||
// Fallback if another load blocked it (rare if user spam clicks)
|
||||
Debug.LogWarning("[UserLogin] SceneLoader returned null (maybe already loading). Attempting fallback GameManager/SceneManager.");
|
||||
if (GameManager.Instance)
|
||||
{
|
||||
GameManager.Instance.LoadSceneWithLoading(MenuSceneName);
|
||||
}
|
||||
else
|
||||
{
|
||||
SceneManager.LoadScene(MenuSceneName);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("[UserLogin] Async operation started (progress will advance automatically)." );
|
||||
}
|
||||
}
|
||||
|
||||
void ShowLoadingIndicator(bool show) { if (loadingIndicator) loadingIndicator.SetActive(show); }
|
||||
void SetFeedback(string msg) { if (feedbackText) feedbackText.text = msg; }
|
||||
void PlayClick() { if (clickSfx) { if (!uiAudio) { uiAudio = gameObject.AddComponent<AudioSource>(); uiAudio.playOnAwake = false; } uiAudio.PlayOneShot(clickSfx); } }
|
||||
|
||||
public void LogoutUser()
|
||||
{ PlayerPrefs.DeleteKey(AuthTokenKey); if (gameInitialize) gameInitialize.SetUserAuthenticated(false); authToken = null; SetFeedback("Logged out."); }
|
||||
|
||||
[System.Serializable] class AuthResponse { public string auth_token; }
|
||||
[System.Serializable] class LoginRequest { public string email; public string password; }
|
||||
}
|
||||
2
Assets/Scripts/Aunthetication/UserLogin.cs.meta
Normal file
2
Assets/Scripts/Aunthetication/UserLogin.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 430bcebc27f4a6c4da036ebc42b18ee2
|
||||
115
Assets/Scripts/Aunthetication/UserRegistration.cs
Normal file
115
Assets/Scripts/Aunthetication/UserRegistration.cs
Normal file
@@ -0,0 +1,115 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
using TMPro;
|
||||
|
||||
public class UserRegistration : MonoBehaviour
|
||||
{
|
||||
public TMP_InputField usernameInput;
|
||||
public TMP_InputField nameInput;
|
||||
public TMP_InputField countryInput;
|
||||
public TMP_InputField emailInput;
|
||||
public TMP_InputField passwordInput;
|
||||
public TMP_InputField rePasswordInput;
|
||||
|
||||
public TextMeshProUGUI feedbackText;
|
||||
|
||||
public GameObject registrationPanel;
|
||||
public GameObject loginPanel;
|
||||
|
||||
private string registerUrl = "http://127.0.0.1:8001/auth/users/";
|
||||
|
||||
public void RegisterUser()
|
||||
{
|
||||
// Debug message for button press
|
||||
Debug.Log("Register button clicked! Starting registration process.");
|
||||
|
||||
// Collect user input
|
||||
string username = usernameInput.text;
|
||||
string name = nameInput.text;
|
||||
string country = countryInput.text;
|
||||
string email = emailInput.text;
|
||||
string password = passwordInput.text;
|
||||
string rePassword = rePasswordInput.text;
|
||||
|
||||
// Log the collected data
|
||||
Debug.Log($"Collected registration data - Username: {username}, Name: {name}, Email: {email}");
|
||||
|
||||
// Validate input
|
||||
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(name) ||
|
||||
string.IsNullOrEmpty(country) || string.IsNullOrEmpty(email) ||
|
||||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(rePassword))
|
||||
{
|
||||
feedbackText.text = "All fields are required!";
|
||||
Debug.Log("Validation failed: Some fields are missing.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (password != rePassword)
|
||||
{
|
||||
feedbackText.text = "Passwords do not match!";
|
||||
Debug.Log("Validation failed: Passwords do not match.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation passed
|
||||
Debug.Log("Validation passed. Starting API call...");
|
||||
StartCoroutine(Register(username, name, country, email, password));
|
||||
}
|
||||
|
||||
private IEnumerator Register(string username, string name, string country, string email, string password)
|
||||
{
|
||||
Debug.Log("Register coroutine started");
|
||||
|
||||
string jsonData = JsonUtility.ToJson(new RegistrationRequest
|
||||
{
|
||||
username = username,
|
||||
name = name,
|
||||
country = country,
|
||||
email = email,
|
||||
password = password,
|
||||
re_password = password
|
||||
});
|
||||
|
||||
Debug.Log($"Sending registration request to: {registerUrl}");
|
||||
Debug.Log($"Request data: {jsonData}");
|
||||
|
||||
using (UnityWebRequest request = new UnityWebRequest(registerUrl, "POST"))
|
||||
{
|
||||
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
|
||||
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
|
||||
request.downloadHandler = new DownloadHandlerBuffer();
|
||||
request.SetRequestHeader("Content-Type", "application/json");
|
||||
|
||||
Debug.Log("Sending web request...");
|
||||
yield return request.SendWebRequest();
|
||||
Debug.Log($"Request completed with result: {request.result}");
|
||||
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
Debug.Log("API call successful. Response: " + request.downloadHandler.text);
|
||||
feedbackText.text = "Registration Successful! Redirecting to login...";
|
||||
registrationPanel.SetActive(false);
|
||||
loginPanel.SetActive(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"API call failed: {request.error}");
|
||||
Debug.LogError($"Response from server: {request.downloadHandler.text}");
|
||||
feedbackText.text = $"Registration failed: {request.downloadHandler.text}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public class RegistrationRequest
|
||||
{
|
||||
public string username;
|
||||
public string name;
|
||||
public string country;
|
||||
public string email;
|
||||
public string password;
|
||||
public string re_password;
|
||||
}
|
||||
2
Assets/Scripts/Aunthetication/UserRegistration.cs.meta
Normal file
2
Assets/Scripts/Aunthetication/UserRegistration.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 43b25d92836f2c649ba0e90035bf3b12
|
||||
Reference in New Issue
Block a user