using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using WXGame.Network;
public class HomeFriendComponent : MonoBehaviour
{
[SerializeField] private RawImage avatarImage; // 头像图片组件
///
/// 初始化好友项数据
///
/// 好友数据
public void InitializeFriendItem(FriendData data)
{
if (data == null)
{
Debug.Log("好友数据为空,无法初始化");
return;
}
Debug.Log($"开始初始化好友项: {data.user_username}");
// 异步下载头像
DownloadAvatarAsync(data.user_image).Forget();
}
///
/// 异步下载头像
///
/// 头像URL
/// UniTask
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}");
}
}
///
/// 设置头像纹理
///
/// 要设置的纹理
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}");
}
}
}