RizzeBattleRoyale/Assets/Scripts/WalletAddressDisplay.cs
2025-10-15 20:28:33 +04:00

84 lines
2.3 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using Reown.AppKit.Unity;
using TMPro;
public class WalletAddressDisplay : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI addressText; // or TMP_Text
[SerializeField] private Button copyButton; // optional
private string _fullAddress = "";
private void Awake()
{
if (copyButton != null) copyButton.onClick.AddListener(CopyToClipboard);
}
private void OnEnable()
{
UpdateLabel(); // show current state immediately
// Subscribe to connection events from the static ConnectorController
if (AppKit.ConnectorController != null)
{
AppKit.ConnectorController.AccountConnected += OnAccountConnected;
AppKit.ConnectorController.AccountDisconnected += OnAccountDisconnected;
}
}
private void OnDisable()
{
if (AppKit.ConnectorController != null)
{
AppKit.ConnectorController.AccountConnected -= OnAccountConnected;
AppKit.ConnectorController.AccountDisconnected -= OnAccountDisconnected;
}
if (copyButton != null) copyButton.onClick.RemoveListener(CopyToClipboard);
}
private void OnAccountConnected(object _, Reown.AppKit.Unity.Connector.AccountConnectedEventArgs __)
{
UpdateLabel();
}
private void OnAccountDisconnected(object _, Reown.AppKit.Unity.Connector.AccountDisconnectedEventArgs __)
{
_fullAddress = "";
SetText("Not connected");
}
private void UpdateLabel()
{
var controller = AppKit.ConnectorController;
if (controller != null && controller.Account != null)
{
_fullAddress = controller.Account.Address;
SetText(Shorten(_fullAddress));
}
else
{
SetText("Not connected");
}
}
private void CopyToClipboard()
{
if (!string.IsNullOrEmpty(_fullAddress))
GUIUtility.systemCopyBuffer = _fullAddress;
}
private static string Shorten(string addr)
{
if (string.IsNullOrEmpty(addr) || addr.Length < 12) return addr;
return addr[..6] + "..." + addr[^4..];
}
private void SetText(string s)
{
if (addressText != null) addressText.text = s;
}
}