using System; using System.Collections.Generic; using System.IO; using Cysharp.Threading.Tasks; using Stary.Evo; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; namespace Script.Util { public static class WebRTCUtil { public static Dictionary _avatarCache = new(); public static Color GetRandomColor() { return new Color( Random.Range(0.2f, 0.8f), Random.Range(0.2f, 0.8f), Random.Range(0.2f, 0.8f), 1f ); } public static async UniTask DownloadAndSetAvatar(string avatarUrl, Image targetImage) { try { if (_avatarCache.TryGetValue(avatarUrl, out var sprite)) { targetImage.sprite = sprite; return; } var tempPath = Path.Combine(Application.temporaryCachePath, $"avatar_{Guid.NewGuid()}.png"); var result = await WebRequestSystem.GetFile(avatarUrl, tempPath); if (result.code == 200) { var bytes = File.ReadAllBytes(tempPath); var texture = new Texture2D(2, 2); texture.LoadImage(bytes); sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f); targetImage.sprite = sprite; File.Delete(tempPath); _avatarCache.TryAdd(avatarUrl, sprite); } } catch (Exception e) { Debug.LogError($"下载头像失败: {e.Message}"); } } } }