Files
test/Assets/Tech3C/Samples/Tech3CSimpleDemo.cs
2026-02-02 19:21:45 +07:00

474 lines
20 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
namespace Tech3C
{
/// <summary>
/// Simple demo that creates UI programmatically
/// Just attach this script to any GameObject in your scene
/// </summary>
public class Tech3CSimpleDemo : MonoBehaviour
{
[Header("Configuration")]
public string clientId = "your_client_id";
public string clientSecret = "your_client_secret";
private Canvas canvas;
private Text logText;
private AuthCallback authCallback;
private LogoutCallback logoutCallback;
private GameObject dialogPanel;
private Text dialogText;
private Button dialogCloseButton;
private void Start()
{
EnsureEventSystem();
CreateUI();
SetupCallbacks();
// Auto-initialize SDK
if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret))
{
Log($"Initializing Tech3C SDK...\n Client ID: {clientId}");
Tech3CSDK.Instance.Initialize(clientId, clientSecret);
if (Tech3CSDK.Instance.IsInitialized)
{
Log("✓ SDK Initialized Successfully!");
}
else
{
Log("✗ Failed to initialize SDK");
}
}
else
{
Log("⚠ Client ID and/or Client Secret not set. Please configure in Inspector.");
}
Debug.Log("[Tech3C Demo] Tech3C SDK Simple Demo Started");
}
private void EnsureEventSystem()
{
if (EventSystem.current == null)
{
GameObject eventSystemGO = new GameObject("EventSystem");
eventSystemGO.AddComponent<EventSystem>();
eventSystemGO.AddComponent<StandaloneInputModule>();
Debug.Log("[Tech3C Demo] EventSystem created");
}
}
private void CreateUI()
{
// Create Canvas
GameObject canvasGO = new GameObject("Tech3CDemoCanvas");
canvasGO.transform.SetParent(transform);
canvas = canvasGO.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
// Configure CanvasScaler for responsive 16:9 ratio
CanvasScaler canvasScaler = canvasGO.AddComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
canvasScaler.referenceResolution = new Vector2(1920, 1080); // 16:9 ratio
canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
canvasScaler.matchWidthOrHeight = 0.5f; // Balance between width and height
canvasGO.AddComponent<GraphicRaycaster>();
// Create Scroll Panel
GameObject scrollPanel = new GameObject("ScrollPanel");
scrollPanel.transform.SetParent(canvasGO.transform, false);
RectTransform scrollPanelRect = scrollPanel.AddComponent<RectTransform>();
scrollPanelRect.anchorMin = Vector2.zero;
scrollPanelRect.anchorMax = Vector2.one;
scrollPanelRect.sizeDelta = Vector2.zero;
Image scrollPanelImage = scrollPanel.AddComponent<Image>();
scrollPanelImage.color = new Color(0.2f, 0.2f, 0.2f, 1f);
// Create ScrollRect
ScrollRect scrollRect = scrollPanel.AddComponent<ScrollRect>();
scrollRect.horizontal = false;
scrollRect.vertical = true;
scrollRect.scrollSensitivity = 50f;
// Create Content Panel
GameObject panel = new GameObject("Content");
panel.transform.SetParent(scrollPanel.transform, false);
RectTransform panelRect = panel.AddComponent<RectTransform>();
panelRect.anchorMin = new Vector2(0, 1);
panelRect.anchorMax = new Vector2(1, 1);
panelRect.pivot = new Vector2(0.5f, 1f);
panelRect.sizeDelta = new Vector2(0, 0);
scrollRect.content = panelRect;
// Create Vertical Layout Group
VerticalLayoutGroup layoutGroup = panel.AddComponent<VerticalLayoutGroup>();
layoutGroup.childControlHeight = false;
layoutGroup.childControlWidth = true;
layoutGroup.childForceExpandWidth = true;
layoutGroup.childForceExpandHeight = false;
layoutGroup.spacing = 15;
layoutGroup.padding = new RectOffset(40, 40, 40, 40);
ContentSizeFitter contentSizeFitter = panel.AddComponent<ContentSizeFitter>();
contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
// Create Title
CreateTextResponsive(panel.transform, "Tech3C SDK Demo", 28, TextAnchor.MiddleCenter, 60);
// Create Separator
CreateTextResponsive(panel.transform, "--- Authentication ---", 18, TextAnchor.MiddleCenter, 30);
// Create Show Auth Button
Button showAuthButton = CreateButtonResponsive(panel.transform, "Show Auth Screen", 70);
showAuthButton.onClick.AddListener(OnShowAuthClick);
// Create Logout Button
Button logoutButton = CreateButtonResponsive(panel.transform, "Logout", 70);
logoutButton.onClick.AddListener(OnLogoutClick);
// Create Log Text
CreateTextResponsive(panel.transform, "Logs:", 16, TextAnchor.MiddleLeft, 35);
logText = CreateTextResponsive(panel.transform, "Ready...", 16, TextAnchor.MiddleLeft, 400);
logText.color = Color.green;
// Reposition panel
panelRect.anchoredPosition = Vector2.zero;
}
private void SetupCallbacks()
{
// Auth callback
authCallback = new AuthCallback();
authCallback.OnAuthSuccessEvent += (userId, password, accessToken, refreshToken, loginType, expiryTime) =>
{
Debug.Log($"[Tech3C Demo] === AUTH SUCCESS CALLBACK FIRED ===");
Debug.Log($"[Tech3C Demo] UserId: {userId}");
Debug.Log($"[Tech3C Demo] Password: {password?.Substring(0, Math.Min(3, password?.Length ?? 0))}...");
Debug.Log($"[Tech3C Demo] LoginType: {loginType}");
Debug.Log($"[Tech3C Demo] AccessToken: {accessToken?.Substring(0, Math.Min(20, accessToken?.Length ?? 0))}...");
Debug.Log($"[Tech3C Demo] RefreshToken: {refreshToken?.Substring(0, Math.Min(20, refreshToken?.Length ?? 0))}...");
Debug.Log($"[Tech3C Demo] ExpiryTime: {expiryTime}");
Log($"✓ Auth Success!\n User ID: {userId}\n Password: {password}\n Login Type: {loginType}\n Token: {accessToken?.Substring(0, Math.Min(20, accessToken?.Length ?? 0))}...");
ShowAuthSuccessDialog(userId, password, loginType.ToString());
};
authCallback.OnAuthCancelledEvent += () =>
{
Debug.Log($"[Tech3C Demo] === AUTH CANCELLED CALLBACK FIRED ===");
Log("✗ Auth Cancelled by user");
};
authCallback.OnAuthErrorEvent += (errorCode, errorMessage) =>
{
Debug.Log($"[Tech3C Demo] === AUTH ERROR CALLBACK FIRED ===");
Debug.Log($"[Tech3C Demo] ErrorCode: {errorCode}");
Debug.Log($"[Tech3C Demo] ErrorMessage: {errorMessage}");
Log($"✗ Auth Error [{errorCode}]: {errorMessage}");
};
// Logout callback
logoutCallback = new LogoutCallback();
logoutCallback.OnLogoutSuccessEvent += () =>
{
Debug.Log($"[Tech3C Demo] === LOGOUT SUCCESS CALLBACK FIRED ===");
Log("✓ Logout Successful");
};
logoutCallback.OnLogoutErrorEvent += (errorCode, errorMessage) =>
{
Debug.Log($"[Tech3C Demo] === LOGOUT ERROR CALLBACK FIRED ===");
Debug.Log($"[Tech3C Demo] ErrorCode: {errorCode}");
Debug.Log($"[Tech3C Demo] ErrorMessage: {errorMessage}");
Log($"✗ Logout Error [{errorCode}]: {errorMessage}");
};
}
#region Button Handlers
private void OnInitializeClick(string newClientId, string newClientSecret)
{
if (string.IsNullOrEmpty(newClientId) || string.IsNullOrEmpty(newClientSecret))
{
Log("✗ Client ID and Client Secret are required!");
return;
}
clientId = newClientId;
clientSecret = newClientSecret;
Log($"Initializing Tech3C SDK...\n Client ID: {clientId}");
Tech3CSDK.Instance.Initialize(clientId, clientSecret);
if (Tech3CSDK.Instance.IsInitialized)
{
Log("✓ SDK Initialized Successfully!");
}
else
{
Log("✗ Failed to initialize SDK");
}
}
private void OnShowAuthClick()
{
if (!Tech3CSDK.Instance.IsInitialized)
{
Log("✗ SDK not initialized. Click Initialize first!");
return;
}
Log("Opening Auth Screen...");
Tech3CSDK.Instance.ShowAuth(authCallback);
}
private void OnLogoutClick()
{
if (!Tech3CSDK.Instance.IsInitialized)
{
Log("✗ SDK not initialized.");
return;
}
Log("Logging out...");
Tech3CSDK.Instance.Logout(logoutCallback);
}
#endregion
#region UI Helper Methods
private Button CreateButton(Transform parent, string text, float width, float height)
{
GameObject buttonGO = new GameObject(text.Replace(" ", "_"));
buttonGO.transform.SetParent(parent, false);
RectTransform rect = buttonGO.AddComponent<RectTransform>();
rect.sizeDelta = new Vector2(width, height);
Image image = buttonGO.AddComponent<Image>();
image.color = new Color(0.3f, 0.5f, 0.8f, 1f);
Button button = buttonGO.AddComponent<Button>();
// Set up button transition for visual feedback
ColorBlock colors = button.colors;
colors.normalColor = new Color(0.3f, 0.5f, 0.8f, 1f);
colors.highlightedColor = new Color(0.4f, 0.6f, 0.9f, 1f);
colors.pressedColor = new Color(0.2f, 0.4f, 0.7f, 1f);
colors.selectedColor = new Color(0.3f, 0.5f, 0.8f, 1f);
colors.colorMultiplier = 1f;
button.colors = colors;
GameObject textGO = new GameObject("Text");
textGO.transform.SetParent(buttonGO.transform, false);
RectTransform textRect = textGO.AddComponent<RectTransform>();
textRect.anchorMin = Vector2.zero;
textRect.anchorMax = Vector2.one;
textRect.sizeDelta = Vector2.zero;
Text textComponent = textGO.AddComponent<Text>();
textComponent.text = text;
textComponent.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
textComponent.fontSize = 18;
textComponent.alignment = TextAnchor.MiddleCenter;
textComponent.color = Color.white;
textComponent.raycastTarget = false; // Important: Allow click to pass through to button
Debug.Log($"[Tech3C Demo] Created button: {text}");
return button;
}
private Text CreateText(Transform parent, string text, int fontSize, TextAnchor alignment, float width, float height)
{
GameObject textGO = new GameObject("Text");
textGO.transform.SetParent(parent, false);
RectTransform rect = textGO.AddComponent<RectTransform>();
rect.sizeDelta = new Vector2(width, height);
Text textComponent = textGO.AddComponent<Text>();
textComponent.text = text;
textComponent.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
textComponent.fontSize = fontSize;
textComponent.alignment = alignment;
textComponent.color = Color.white;
textComponent.raycastTarget = false; // Prevent text from blocking button clicks
return textComponent;
}
private Text CreateLabel(Transform parent, string text)
{
return CreateText(parent, text, 14, TextAnchor.MiddleLeft, 500, 30);
}
private InputField CreateInputField(Transform parent, string defaultValue)
{
GameObject inputGO = new GameObject("InputField");
inputGO.transform.SetParent(parent, false);
RectTransform rect = inputGO.AddComponent<RectTransform>();
rect.sizeDelta = new Vector2(500, 40);
Image image = inputGO.AddComponent<Image>();
image.color = new Color(0.3f, 0.3f, 0.3f, 1f);
InputField inputField = inputGO.AddComponent<InputField>();
inputField.textComponent = CreateText(inputGO.transform, defaultValue, 16, TextAnchor.MiddleLeft, 500, 40);
inputField.textComponent.color = Color.black;
inputField.textComponent.raycastTarget = false; // Prevent text from blocking input
inputField.lineType = InputField.LineType.MultiLineSubmit;
Debug.Log($"[Tech3C Demo] Created input field with default value");
return inputField;
}
private void Log(string message)
{
Debug.Log($"[Tech3C Demo] {message}");
if (logText != null)
{
string timestamp = System.DateTime.Now.ToString("HH:mm:ss");
logText.text = $"[{timestamp}] {message}\n{logText.text}";
}
}
#endregion
#region Responsive UI Helper Methods
private Button CreateButtonResponsive(Transform parent, string text, float height)
{
GameObject buttonGO = new GameObject(text.Replace(" ", "_"));
buttonGO.transform.SetParent(parent, false);
RectTransform rect = buttonGO.AddComponent<RectTransform>();
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(1, 0);
rect.pivot = new Vector2(0.5f, 0.5f);
rect.sizeDelta = new Vector2(-80, height); // -80 for left/right padding
Image image = buttonGO.AddComponent<Image>();
image.color = new Color(0.3f, 0.5f, 0.8f, 1f);
Button button = buttonGO.AddComponent<Button>();
// Set up button transition for visual feedback
ColorBlock colors = button.colors;
colors.normalColor = new Color(0.3f, 0.5f, 0.8f, 1f);
colors.highlightedColor = new Color(0.4f, 0.6f, 0.9f, 1f);
colors.pressedColor = new Color(0.2f, 0.4f, 0.7f, 1f);
colors.selectedColor = new Color(0.3f, 0.5f, 0.8f, 1f);
colors.colorMultiplier = 1f;
button.colors = colors;
GameObject textGO = new GameObject("Text");
textGO.transform.SetParent(buttonGO.transform, false);
RectTransform textRect = textGO.AddComponent<RectTransform>();
textRect.anchorMin = Vector2.zero;
textRect.anchorMax = Vector2.one;
textRect.sizeDelta = Vector2.zero;
Text textComponent = textGO.AddComponent<Text>();
textComponent.text = text;
textComponent.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
textComponent.fontSize = 22;
textComponent.alignment = TextAnchor.MiddleCenter;
textComponent.color = Color.white;
textComponent.raycastTarget = false;
return button;
}
private Text CreateTextResponsive(Transform parent, string text, int fontSize, TextAnchor alignment, float height)
{
GameObject textGO = new GameObject("Text");
textGO.transform.SetParent(parent, false);
RectTransform rect = textGO.AddComponent<RectTransform>();
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(1, 0);
rect.pivot = new Vector2(0.5f, 0.5f);
rect.sizeDelta = new Vector2(0, height);
Text textComponent = textGO.AddComponent<Text>();
textComponent.text = text;
textComponent.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
textComponent.fontSize = fontSize;
textComponent.alignment = alignment;
textComponent.color = Color.white;
textComponent.raycastTarget = false;
return textComponent;
}
private void ShowAuthSuccessDialog(string userId, string password, string loginType)
{
// Remove existing dialog if any
if (dialogPanel != null)
{
Destroy(dialogPanel);
}
// Create dialog background (full screen overlay)
GameObject overlayGO = new GameObject("DialogOverlay");
overlayGO.transform.SetParent(canvas.transform, false);
RectTransform overlayRect = overlayGO.AddComponent<RectTransform>();
overlayRect.anchorMin = Vector2.zero;
overlayRect.anchorMax = Vector2.one;
overlayRect.sizeDelta = Vector2.zero;
Image overlayImage = overlayGO.AddComponent<Image>();
overlayImage.color = new Color(0, 0, 0, 0.7f); // Semi-transparent black
// Create dialog panel
dialogPanel = new GameObject("AuthSuccessDialog");
dialogPanel.transform.SetParent(overlayGO.transform, false);
RectTransform dialogRect = dialogPanel.AddComponent<RectTransform>();
dialogRect.anchorMin = new Vector2(0.3f, 0.4f);
dialogRect.anchorMax = new Vector2(0.7f, 0.6f);
dialogRect.offsetMin = Vector2.zero;
dialogRect.offsetMax = Vector2.zero;
Image dialogImage = dialogPanel.AddComponent<Image>();
dialogImage.color = new Color(0.15f, 0.35f, 0.15f, 1f);
// Create vertical layout group for dialog
VerticalLayoutGroup dialogLayout = dialogPanel.AddComponent<VerticalLayoutGroup>();
dialogLayout.childControlHeight = false;
dialogLayout.childControlWidth = true;
dialogLayout.childForceExpandWidth = true;
dialogLayout.childAlignment = TextAnchor.MiddleCenter;
dialogLayout.spacing = 20;
dialogLayout.padding = new RectOffset(20, 20, 20, 20);
ContentSizeFitter dialogFitter = dialogPanel.AddComponent<ContentSizeFitter>();
dialogFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
// Create success message
Text successTitle = CreateText(dialogPanel.transform, "✓ LOGIN SUCCESSFUL", 32, TextAnchor.MiddleCenter, 400, 50);
successTitle.color = Color.green;
// Create user info
string userInfoText = $"User ID: {userId}\nPassword: {password}\nLogin Type: {loginType}";
Text userInfoComponent = CreateText(dialogPanel.transform, userInfoText, 20, TextAnchor.MiddleCenter, 400, 80);
userInfoComponent.color = Color.white;
// Create close button
dialogCloseButton = CreateButton(dialogPanel.transform, "OK", 200, 50);
dialogCloseButton.onClick.AddListener(() =>
{
Debug.Log("[Tech3C Demo] Dialog close button clicked");
Destroy(overlayGO);
dialogPanel = null;
});
}
#endregion
}
}