Unity中通过Facebook API获取用户名及头像,头像空白无报错如何解决?
修复方案
1. 修正头像接口请求参数
当前你调用的/me/picture?type=med接口默认会触发302重定向到真实图片地址,Facebook Unity SDK的IGraphResult不会自动跟进重定向拉取纹理,所以会出现无报错但result.Texture为空的问题。你需要修改请求URL添加redirect=false参数,先拿到图片的真实访问地址,再自行加载纹理。
修改后的请求逻辑参考:
void DealWithFbMenus(bool isLoggedIn) { if (isLoggedIn) { FB.API("/me?fields=first_name", HttpMethod.GET, DisplayUsername); // 修改头像请求地址,添加redirect=false参数 FB.API("/me/picture?type=med&redirect=false", HttpMethod.GET, GetProfilePicUrl); } }
新增图片地址解析与纹理加载逻辑:
using UnityEngine.Networking; // 需要先引入网络请求命名空间 void GetProfilePicUrl(IGraphResult result) { if (result.Error == null && result.ResultDictionary.TryGetValue("data", out object dataObj)) { var data = dataObj as Dictionary<string, object>; string picUrl = data["url"].ToString(); StartCoroutine(LoadProfilePicCoroutine(picUrl)); } else { Debug.LogError($"获取头像地址失败:{result.Error}"); } } IEnumerator LoadProfilePicCoroutine(string picUrl) { using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(picUrl)) { yield return req.SendWebRequest(); if (req.result == UnityWebRequest.Result.Success) { Texture2D profileTex = DownloadHandlerTexture.GetContent(req); // 修复Sprite创建参数:用纹理实际尺寸,锚点设为居中(0.5,0.5) FB_userDp.sprite = Sprite.Create(profileTex, new Rect(0, 0, profileTex.width, profileTex.height), new Vector2(0.5f, 0.5f)); } else { Debug.LogError($"加载头像纹理失败:{req.error}"); } } }
2. 原有代码的隐藏问题修复
你原有创建Sprite的逻辑存在两个可能导致显示空白的问题:
- 固定写死了
128*128的裁剪尺寸,如果实际返回的纹理尺寸和这个值不符,会出现裁剪异常甚至完全空白 - 锚点参数用了空的
new Vector2(),实际等价于锚点在左下角,如果你的Image组件锚点是居中设置,Sprite会渲染到视野外看起来是空的
上面的修复代码已经解决了这两个问题,直接用纹理实际尺寸,锚点设为居中即可。
3. 额外校验排查
如果修改后还是有问题,可以加日志确认关键节点状态:
- 确认
FB_userDp组件已经正确挂载,不是空引用 - 确认Image组件的颜色透明度是1,没有被设置成全透明
- 加日志打印
picUrl和纹理加载结果,确认资源能正常访问
内容的提问来源于stack exchange,提问作者Vipul Rathod
相关产品推荐
相关产品推荐

