用Unity开发微信小游戏获取用户信息必须要用户主动点击触发按钮才会弹出授权信息提示弹窗,网上的代码都是点击全屏或者底部区域300高度的代码实现,不能满足项目需求,于是自己写了一个,经测试可以与Unity中的UI按钮完美匹配,以下是具体实现代码:
public Button StartBtn; //开始按钮
private WXUserInfo _wxUserInfo; //用户信息
/// <summary>
/// 创建用户信息授权点击按钮
/// </summary>
private void CreateUserInfoButton()
{
var systemInfo = WX.GetSystemInfoSync();
Debug.Log($"屏幕宽度: {systemInfo.screenWidth}, 屏幕高度: {systemInfo.screenHeight}, 像素比率: {systemInfo.pixelRatio}");
// 获取 Unity UI Button 的 RectTransform
RectTransform rectTransform = StartBtn.GetComponent<RectTransform>();
// 将 RectTransform 的世界坐标转换为屏幕坐标
Vector2 screenPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, rectTransform.position);
Vector2 sizeDelta = rectTransform.sizeDelta;
// 强制将 systemInfo 的属性转换为 float 类型,并转换为像素单位
float pixelRatio = (float)systemInfo.pixelRatio;
float screenHeight = (float)systemInfo.screenHeight * pixelRatio; // 转换为像素
// 计算按钮在像素坐标系中的宽度和高度
float buttonWidthFloat = sizeDelta.x * pixelRatio;
float buttonHeightFloat = sizeDelta.y * pixelRatio;
// 计算按钮中心点的像素坐标
float buttonXFloat = screenPosition.x - (buttonWidthFloat / 2f);
float buttonYFloat = screenHeight - screenPosition.y - (buttonHeightFloat / 2f);
// 使用 Mathf.RoundToInt 将 float 转换为 int
int posX = Mathf.RoundToInt(buttonXFloat);
int posY = Mathf.RoundToInt(buttonYFloat);
int width = Mathf.RoundToInt(buttonWidthFloat);
int height = Mathf.RoundToInt(buttonHeightFloat);
Debug.Log($"WXUserInfoButton 位置和大小 - X: {posX}, Y: {posY}, 宽度: {width}, 高度: {height}");
// 创建 WeChat User Info Button
WXUserInfoButton infoButton = WX.CreateUserInfoButton(posX, posY, width, height, "zh_CN", false);
// 监听授权区域的点击
infoButton.OnTap((res) =>
{
Debug.Log("click userinfo btn");
if (res.errCode == 0)
{
// 用户已允许获取个人信息,返回的 res.userInfo 即为用户信息
Debug.Log("userinfo: " + JsonUtility.ToJson(res.userInfo, true));
// 将用户信息存入成员变量
_wxUserInfo = res.userInfo;
}
else
{
Debug.Log("用户拒绝获取个人信息");
}
// 最后隐藏授权区域,防止阻塞游戏继续
infoButton.Hide();
if (StartBtn != null)
{
StartBtn.onClick.Invoke();
}
});
}