WX-Game1/Assets/Scripts/Component/HomeFriendComponent.cs

90 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using WXGame.Network;
public class HomeFriendComponent : MonoBehaviour
{
[SerializeField] private RawImage avatarImage; // 头像图片组件
/// <summary>
/// 初始化好友项数据
/// </summary>
/// <param name="data">好友数据</param>
public void InitializeFriendItem(FriendData data)
{
if (data == null)
{
Debug.Log("好友数据为空,无法初始化");
return;
}
Debug.Log($"开始初始化好友项: {data.user_username}");
// 异步下载头像
DownloadAvatarAsync(data.user_image).Forget();
}
/// <summary>
/// 异步下载头像
/// </summary>
/// <param name="imageUrl">头像URL</param>
/// <returns>UniTask</returns>
private async UniTask DownloadAvatarAsync(string imageUrl)
{
try
{
// 检查URL是否有效
if (string.IsNullOrEmpty(imageUrl))
{
Debug.Log("头像URL为空使用默认头像");
return;
}
Debug.Log($"开始下载头像: {imageUrl}");
// 使用WebRequestManager下载图片
Texture2D texture = await WebRequestManager.Instance.DownloadImageAsync(imageUrl);
if (texture != null)
{
// 设置头像
SetAvatarTexture(texture);
Debug.Log($"头像设置完成,尺寸: {texture.width}x{texture.height}");
}
else
{
Debug.Log("头像下载失败,使用默认头像");
}
}
catch (Exception ex)
{
Debug.Log($"下载头像时发生异常: {ex.Message}");
}
}
/// <summary>
/// 设置头像纹理
/// </summary>
/// <param name="texture">要设置的纹理</param>
private void SetAvatarTexture(Texture2D texture)
{
try
{
if (avatarImage != null && texture != null)
{
avatarImage.texture = texture;
Debug.Log("头像纹理设置成功");
}
else
{
Debug.Log("头像图片组件未设置或纹理为空");
}
}
catch (Exception ex)
{
Debug.Log($"设置头像纹理时发生异常: {ex.Message}");
}
}
}