当前位置:   article > 正文

Unity微信小游戏常用API总结_wx.getwxfont

wx.getwxfont

获取用户信息

游戏初始化,想要获取玩家的信息还需要在mp中进行隐私设置。

  1. WX.InitSDK((code) =>
  2. {
  3. // 打印屏幕信息
  4. var systemInfo = WX.GetSystemInfoSync();
  5. Debug.Log($"{systemInfo.screenWidth}:{systemInfo.screenHeight}, {systemInfo.windowWidth}:{systemInfo.windowHeight}, {systemInfo.pixelRatio}");
  6. // 创建用户信息获取按钮,在底部区域创建一个300高度的透明区域
  7. // 首次获取会弹出用户授权窗口, 可通过右上角-设置-权限管理用户的授权记录
  8. var canvasWith = (int)(systemInfo.screenWidth * systemInfo.pixelRatio);
  9. var canvasHeight = (int)(systemInfo.screenHeight * systemInfo.pixelRatio);
  10. var buttonHeight = (int)(canvasWith / 1080f * 300f);
  11. infoButton = WX.CreateUserInfoButton(0, canvasHeight - buttonHeight, canvasWith, buttonHeight, "zh_CN", false);
  12. infoButton.OnTap((userInfoButonRet) =>
  13. {
  14. Debug.Log(JsonUtility.ToJson(userInfoButonRet.userInfo));
  15. txtUserInfo.text = $"nickName:{userInfoButonRet.userInfo.nickName}, avartar:{userInfoButonRet.userInfo.avatarUrl}";
  16. //userInfoButonRet.userInfo.nickName 获取用户昵称
  17. //userInfoButonRet.userInfo.avatarUrl 获取用户图片
  18. });
  19. Debug.Log("infoButton Created");
  20. });

游戏分享

  1. public void OnShareClick()
  2. {
  3. WX.ShareAppMessage(new ShareAppMessageOption()
  4. {
  5. title = "分享标题xxx",
  6. imageUrl = "https://inews.gtimg.com/newsapp_bt/0/12171811596_909/0",
  7. });
  8. }

利用PlayerPref数据持久化

  1. // 注意!!! PlayerPrefs为同步接口,iOS高性能模式下为"跨进程"同步调用,会阻塞游戏线程,请避免频繁调用
  2. PlayerPrefs.SetString("mystringkey", "myestringvalue");
  3. PlayerPrefs.SetInt("myintkey", 123);
  4. PlayerPrefs.SetFloat("myfloatkey", 1.23f);
  5. Debug.Log($"PlayerPrefs mystringkey:{PlayerPrefs.GetString("mystringkey")}");
  6. Debug.Log($"PlayerPrefs myintkey:{PlayerPrefs.GetInt("myintkey")}");
  7. Debug.Log($"PlayerPrefs myfloatkey:{PlayerPrefs.GetFloat("myfloatkey")}");

文本输入框调用手机键盘输入

将脚本挂载在InputField上即可。

  1. public class Inputs : MonoBehaviour, IPointerClickHandler, IPointerExitHandler
  2. {
  3. public InputField input;
  4. public Text text;
  5. private bool isShowKeyboad = false;
  6. public void OnPointerClick(PointerEventData eventData)
  7. {
  8. ShowKeyboad();
  9. }
  10. public void OnPointerExit(PointerEventData eventData)
  11. {
  12. // 隐藏输入法
  13. if (!input.isFocused)
  14. {
  15. HideKeyboad();
  16. }
  17. }
  18. public void OnInput(OnKeyboardInputListenerResult v)
  19. {
  20. Debug.Log("onInput");
  21. Debug.Log(v.value);
  22. text.text = v.value;
  23. if (input.isFocused)
  24. {
  25. input.text = v.value;
  26. }
  27. }
  28. public void OnConfirm(OnKeyboardInputListenerResult v)
  29. {
  30. // 输入法confirm回调
  31. Debug.Log("onConfirm");
  32. Debug.Log(v.value);
  33. HideKeyboad();
  34. }
  35. public void OnComplete(OnKeyboardInputListenerResult v)
  36. {
  37. // 输入法complete回调
  38. Debug.Log("OnComplete");
  39. Debug.Log(v.value);
  40. HideKeyboad();
  41. }
  42. private void ShowKeyboad()
  43. {
  44. if (!isShowKeyboad)
  45. {
  46. WX.ShowKeyboard(new ShowKeyboardOption()
  47. {
  48. defaultValue = "",
  49. maxLength = 20,
  50. confirmType = "go"
  51. });
  52. //绑定回调
  53. WX.OnKeyboardConfirm(OnConfirm);
  54. WX.OnKeyboardComplete(OnComplete);
  55. WX.OnKeyboardInput(OnInput);
  56. isShowKeyboad = true;
  57. }
  58. }
  59. private void HideKeyboad()
  60. {
  61. if (isShowKeyboad)
  62. {
  63. WX.HideKeyboard(new HideKeyboardOption());
  64. //删除掉相关事件监听
  65. WX.OffKeyboardInput(OnInput);
  66. WX.OffKeyboardConfirm(OnConfirm);
  67. WX.OffKeyboardComplete(OnComplete);
  68. isShowKeyboad = false;
  69. }
  70. }
  71. }

音效控制

  1. public class AudioManager : MonoBehaviour
  2. {
  3. public AudioSource AudioSource;
  4. public AudioClip AudioClipLong;
  5. public AudioClip AudioClipShort;
  6. public Slider VolumeSlider;
  7. private void Start()
  8. {
  9. VolumeSlider.value = AudioSource.volume;
  10. VolumeSlider.onValueChanged.AddListener((_) =>
  11. {
  12. OnVolumeChanged(_);
  13. });
  14. }
  15. void OnVolumeChanged(float volume)
  16. {
  17. AudioSource.volume = volume;
  18. }
  19. /// <summary>
  20. /// 循环播放
  21. /// </summary>
  22. public void PlayLong()
  23. {
  24. AudioSource.clip = AudioClipLong;
  25. AudioSource.loop = true;
  26. AudioSource.Play();
  27. }
  28. /// <summary>
  29. /// 播放一次
  30. /// </summary>
  31. public void PlayShort()
  32. {
  33. AudioSource.clip = AudioClipShort;
  34. AudioSource.loop = false;
  35. AudioSource.Play();
  36. }
  37. /// <summary>
  38. /// 暂停播放
  39. /// </summary>
  40. public void Pause()
  41. {
  42. AudioSource.Pause();
  43. }
  44. /// <summary>
  45. /// 恢复播放
  46. /// </summary>
  47. public void Resume()
  48. {
  49. AudioSource.UnPause();
  50. }
  51. /// <summary>
  52. /// 关闭声音
  53. /// </summary>
  54. public void Stop()
  55. {
  56. AudioSource.Stop();
  57. }
  58. }

获取微信字体

  1. // fallbackFont作为旧版本微信或者无法获得系统字体文件时的备选CDN URL
  2. var fallbackFont = Application.streamingAssetsPath + "/Fz.ttf";
  3. WX.GetWXFont(fallbackFont, (font) =>
  4. {
  5. if (font != null)
  6. {
  7. txtTestWXFont.font = font;
  8. }
  9. });

微信文件系统存储

  1. public void OnFileSystemManagerClick()
  2. {
  3. // 扫描文件系统目录
  4. fs.Stat(new WXStatOption
  5. {
  6. path = env.USER_DATA_PATH + "/__GAME_FILE_CACHE",
  7. recursive = true,
  8. success = (succ) =>
  9. {
  10. Debug.Log($"stat success");
  11. foreach (var file in succ.stats)
  12. {
  13. Debug.Log($"stat info. {file.path}, " +
  14. $"{file.stats.size}," +
  15. $"{file.stats.mode}," +
  16. $"{file.stats.lastAccessedTime}," +
  17. $"{file.stats.lastModifiedTime}");
  18. }
  19. },
  20. fail = (fail) =>
  21. {
  22. Debug.Log($"stat fail {fail.errMsg}");
  23. }
  24. });
  25. // 同步接口创建目录(请勿在游戏过程中频繁调用同步接口)
  26. var errMsg = fs.MkdirSync(env.USER_DATA_PATH + "/mydir", true);
  27. // 异步写入文件
  28. fs.WriteFile(new WriteFileParam
  29. {
  30. filePath = env.USER_DATA_PATH + "/mydir/myfile.txt",
  31. encoding = "utf8",
  32. data = System.Text.Encoding.UTF8.GetBytes("Test FileSystemManager"),
  33. success = (succ) =>
  34. {
  35. Debug.Log($"WriteFile succ {succ.errMsg}");
  36. // 异步读取文件
  37. fs.ReadFile(new ReadFileParam
  38. {
  39. filePath = env.USER_DATA_PATH + "/mydir/myfile.txt",
  40. encoding = "utf8",
  41. success = (succ) =>
  42. {
  43. Debug.Log($"ReadFile succ. stringData(utf8):{succ.stringData}");
  44. },
  45. fail = (fail) =>
  46. {
  47. Debug.Log($"ReadFile fail {fail.errMsg}");
  48. }
  49. });
  50. // 异步以无编码(二进制)方式读取
  51. fs.ReadFile(new ReadFileParam
  52. {
  53. filePath = env.USER_DATA_PATH + "/mydir/myfile.txt",
  54. encoding = "",
  55. success = (succ) =>
  56. {
  57. Debug.Log($"ReadFile succ. data(binary):{succ.binData.Length}, stringData(utf8):{System.Text.Encoding.UTF8.GetString(succ.binData)}");
  58. },
  59. fail = (fail) =>
  60. {
  61. Debug.Log($"ReadFile fail {fail.errMsg}");
  62. }
  63. });
  64. },
  65. fail = (fail) =>
  66. {
  67. Debug.Log($"WriteFile fail {fail.errMsg}");
  68. },
  69. complete = null
  70. });
  71. }

获取微信用户唯一标识OpenId

  1. /// <summary>
  2. /// 调用云函数获取用户OpenID
  3. /// </summary>
  4. /// <returns></returns>
  5. IEnumerator CallFunc()
  6. {
  7. WX.cloud.Init(new CallFunctionInitParam{
  8. env="cloud1-2gdeopavbdf6d731",
  9. });
  10. WX.cloud.CallFunction(new CallFunctionParam
  11. {
  12. name = "login",
  13. data = "{}",
  14. success = (res) =>
  15. {
  16. Debug.Log("[云函数] [login] user openid: " + res.result);
  17. if (!string.IsNullOrEmpty(res.result))
  18. {
  19. Dictionary<string, object> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(res.result);
  20. Debug.Log("真正获取openid:" + jsonDict["openid"].ToString());
  21. }
  22. },
  23. fail = (err) =>
  24. {
  25. Debug.Log("Fail" + err.result);
  26. }
  27. });
  28. yield return null;
  29. }
  30. /// <summary>
  31. /// 利用UnityWebRequest获取
  32. /// </summary>
  33. /// <returns></returns>
  34. IEnumerator GetAccessToken()
  35. {
  36. bool flag = true;
  37. string jsCode = "";
  38. WX.Login(new LoginOption
  39. {
  40. success = (res) => {
  41. jsCode = res.code;
  42. }
  43. ,
  44. complete = (res) =>
  45. {
  46. flag = false;
  47. }
  48. });
  49. while (flag)
  50. {
  51. yield return null;
  52. }
  53. string url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx87659b52c2900cfb&secret=7593e6c0fe683d4ac03828e59cadd566&js_code=" + jsCode+"&grant_type=authorization_code";
  54. Debug.Log(url);
  55. UnityWebRequest request = UnityWebRequest.Get(url);
  56. yield return request.SendWebRequest();
  57. if(string.IsNullOrEmpty(request.error))
  58. {
  59. // access token获取成功,将结果发送给Unity游戏
  60. Debug.Log(request.downloadHandler.text);
  61. OnAccessTokenReceived(request.downloadHandler.text);
  62. }
  63. else
  64. {
  65. // 获取access token失败
  66. Debug.Log(request.error);
  67. }
  68. }
  69. public void OnAccessTokenReceived(string json)
  70. {
  71. // 将json字符串反序列化为AccessTokenResponse对象
  72. AccessTokenResponse accessTokenResponse = JsonUtility.FromJson<AccessTokenResponse>(json);
  73. if (accessTokenResponse.access_token != null)
  74. {
  75. // access token获取成功,可以在这里实现验证和其他操作。
  76. Debug.Log("Access token received: " + accessTokenResponse.access_token
  77. +"OpenID:"+ accessTokenResponse.openid
  78. );
  79. }
  80. else
  81. {
  82. // access token获取失败
  83. Debug.Log("Error: " + accessTokenResponse.errmsg);
  84. }
  85. }
  86. [System.Serializable]
  87. public class AccessTokenResponse
  88. {
  89. public string access_token;
  90. public int expires_in;
  91. public string refresh_token;
  92. public string openid;
  93. public string scope;
  94. public string errcode;
  95. public string errmsg;
  96. }

各种广告的api

  1. using UnityEngine;
  2. using WeChatWASM;
  3. public class ADManager : MonoBehaviour
  4. {
  5. public WXBannerAd BannerAd;
  6. public WXRewardedVideoAd RewardedVideoAd;
  7. public WXCustomAd CustomAd;
  8. private void Start()
  9. {
  10. WX.InitSDK((code) =>
  11. {
  12. CreateBannerAd();
  13. CreateRewardedVideoAd();
  14. CreateCustomAd();
  15. });
  16. }
  17. /// <summary>
  18. /// 创建一个固定在底部的广告
  19. /// </summary>
  20. private void CreateBannerAd()
  21. {
  22. BannerAd = WX.CreateFixedBottomMiddleBannerAd("adunit-c0b06553f23c5081", 30, 200);
  23. }
  24. public void ShowBannerAd()
  25. {
  26. BannerAd.Show((suc) => {
  27. Debug.Log("显示成功");
  28. }, (fail) => {
  29. Debug.Log("显示失败");
  30. });
  31. }
  32. public void HideBannerAd()
  33. {
  34. BannerAd.Hide();
  35. }
  36. public void DestroyBannerAd()
  37. {
  38. BannerAd.Destroy();
  39. }
  40. /// <summary>
  41. /// 创建一个激励视频广告
  42. /// </summary>
  43. private void CreateRewardedVideoAd()
  44. {
  45. RewardedVideoAd = WX.CreateRewardedVideoAd(new WXCreateRewardedVideoAdParam()
  46. {
  47. adUnitId = "adunit-f8bd4231b2720db6",
  48. });
  49. RewardedVideoAd.OnLoad((res) =>
  50. {
  51. Debug.Log("RewardedVideoAd.OnLoad:" + JsonUtility.ToJson(res));
  52. var reportShareBehaviorRes = RewardedVideoAd.ReportShareBehavior(new RequestAdReportShareBehaviorParam()
  53. {
  54. operation = 1,
  55. currentShow = 1,
  56. strategy = 0,
  57. shareValue = res.shareValue,
  58. rewardValue = res.rewardValue,
  59. depositAmount = 100,
  60. });
  61. Debug.Log("ReportShareBehavior.Res:" + JsonUtility.ToJson(reportShareBehaviorRes));
  62. });
  63. RewardedVideoAd.OnError((err) =>
  64. {
  65. Debug.Log("RewardedVideoAd.OnError:" + JsonUtility.ToJson(err));
  66. });
  67. RewardedVideoAd.OnClose((res) =>
  68. {
  69. Debug.Log("RewardedVideoAd.OnClose:" + JsonUtility.ToJson(res));
  70. });
  71. RewardedVideoAd.Load();
  72. }
  73. public void ShowRewardedVideoAd()
  74. {
  75. RewardedVideoAd.Show();
  76. }
  77. public void DestroyRewardedVideoAd()
  78. {
  79. RewardedVideoAd.Destroy();
  80. }
  81. /// <summary>
  82. /// 自定义广告类型
  83. /// </summary>
  84. private void CreateCustomAd()
  85. {
  86. CustomAd = WX.CreateCustomAd(new WXCreateCustomAdParam()
  87. {
  88. adUnitId = "adunit-2f150d9a6500399d",
  89. adIntervals = 30,
  90. style = {
  91. left = 0,
  92. top = 100,
  93. },
  94. });
  95. CustomAd.OnLoad((res) =>
  96. {
  97. Debug.Log("CustomAd.OnLoad:" + JsonUtility.ToJson(res));
  98. });
  99. CustomAd.OnError((res) =>
  100. {
  101. Debug.Log("CustomAd.onError:" + JsonUtility.ToJson(res));
  102. });
  103. CustomAd.OnHide(() =>
  104. {
  105. Debug.Log("CustomAd.onHide:");
  106. });
  107. CustomAd.OnClose(() =>
  108. {
  109. Debug.Log("CustomAd.onClose");
  110. });
  111. }
  112. public void ShowCustomAd()
  113. {
  114. CustomAd.Show();
  115. }
  116. public void HideCustomAd()
  117. {
  118. CustomAd.Hide();
  119. }
  120. public void DestroyCustomAd()
  121. {
  122. CustomAd.Destroy();
  123. }
  124. private void OnDestroy()
  125. {
  126. DestroyBannerAd();
  127. DestroyRewardedVideoAd();
  128. DestroyCustomAd();
  129. }
  130. }

微信排行榜

官方文档

  1. using System.IO;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.SceneManagement;
  6. using UnityEngine.UI;
  7. using WeChatWASM;
  8. [System.Serializable]
  9. public class OpenDataMessage
  10. {
  11. // type 用于表明时间类型
  12. public string type;
  13. public string shareTicket;
  14. public int score;
  15. }
  16. public class Ranking : MonoBehaviour
  17. {
  18. public Button ShowButton;
  19. public Button ShareButton;
  20. public Button ReportButton;
  21. public RawImage RankBody;
  22. public GameObject RankMask;
  23. public GameObject RankingBox;
  24. void Start()
  25. {
  26. WX.InitSDK((code) =>
  27. {
  28. Init();
  29. });
  30. /**
  31. * 使用群排行功能需要特殊设置分享功能,详情可见链接
  32. * https://developers.weixin.qq.com/minigame/dev/guide/open-ability/share/share.html
  33. */
  34. WX.UpdateShareMenu(new UpdateShareMenuOption()
  35. {
  36. withShareTicket = true,
  37. isPrivateMessage = true,
  38. });
  39. /**
  40. * 群排行榜功能需要配合 WX.OnShow 来使用,整体流程为:
  41. * 1. WX.UpdateShareMenu 分享功能;
  42. * 2. 监听 WX.OnShow 回调,如果存在 shareTicket 且 query 里面带有启动特定 query 参数则为需要展示群排行的场景
  43. * 3. 调用 WX.ShowOpenData 和 WX.GetOpenDataContext().PostMessage 告知开放数据域侧需要展示群排行信息
  44. * 4. 开放数据域调用 wx.getGroupCloudStorage 接口拉取获取群同玩成员的游戏数据
  45. * 5. 将群同玩成员数据绘制到 sharedCanvas
  46. */
  47. WX.OnShow((OnShowCallbackResult res) =>
  48. {
  49. string shareTicket = res.shareTicket;
  50. Dictionary<string, string> query = res.query;
  51. if (!string.IsNullOrEmpty(shareTicket) && query != null && query["minigame_action"] == "show_group_list")
  52. {
  53. OpenDataMessage msgData = new OpenDataMessage();
  54. msgData.type = "showGroupFriendsRank";
  55. msgData.shareTicket = shareTicket;
  56. string msg = JsonUtility.ToJson(msgData);
  57. ShowOpenData();
  58. WX.GetOpenDataContext().PostMessage(msg);
  59. }
  60. });
  61. }
  62. void ShowOpenData()
  63. {
  64. RankMask.SetActive(true);
  65. RankingBox.SetActive(true);
  66. //
  67. // 注意这里传x,y,width,height是为了点击区域能正确点击,x,y 是距离屏幕左上角的距离,宽度传 (int)RankBody.rectTransform.rect.width是在canvas的UI Scale Mode为 Constant Pixel Size的情况下设置的。
  68. /**
  69. * 如果父元素占满整个窗口的话,pivot 设置为(0,0),rotation设置为180,则左上角就是离屏幕的距离
  70. * 注意这里传x,y,width,height是为了点击区域能正确点击,因为开放数据域并不是使用 Unity 进行渲染而是可以选择任意第三方渲染引擎
  71. * 所以开放数据域名要正确处理好事件处理,就需要明确告诉开放数据域,排行榜所在的纹理绘制在屏幕中的物理坐标系
  72. * 比如 iPhone Xs Max 的物理尺寸是 414 * 896,如果排行榜被绘制在屏幕中央且物理尺寸为 200 * 200,那么这里的 x,y,width,height应当是 107,348,200,200
  73. * x,y 是距离屏幕左上角的距离,宽度传 (int)RankBody.rectTransform.rect.width是在canvas的UI Scale Mode为 Constant Pixel Size的情况下设置的
  74. * 如果是Scale With Screen Size,且设置为以宽度作为缩放,则要这要做一下换算,比如canavs宽度为960,rawImage设置为200 则需要根据 referenceResolution 做一些换算
  75. * 不过不管是什么屏幕适配模式,这里的目的就是为了算出 RawImage 在屏幕中绝对的位置和尺寸
  76. */
  77. CanvasScaler scaler = gameObject.GetComponent<CanvasScaler>();
  78. var referenceResolution = scaler.referenceResolution;
  79. var p = RankBody.transform.position;
  80. WX.ShowOpenData(RankBody.texture, (int)p.x, Screen.height - (int)p.y, (int)((Screen.width / referenceResolution.x) * RankBody.rectTransform.rect.width), (int)((Screen.width / referenceResolution.x) * RankBody.rectTransform.rect.height));
  81. }
  82. void Init()
  83. {
  84. ShowButton.onClick.AddListener(() =>
  85. {
  86. ShowOpenData();
  87. OpenDataMessage msgData = new OpenDataMessage();
  88. msgData.type = "showFriendsRank";
  89. string msg = JsonUtility.ToJson(msgData);
  90. WX.GetOpenDataContext().PostMessage(msg);
  91. });
  92. RankMask.GetComponent<Button>().onClick.AddListener(() =>
  93. {
  94. RankMask.SetActive(false);
  95. RankingBox.SetActive(false);
  96. WX.HideOpenData();
  97. });
  98. ShareButton.onClick.AddListener(() =>
  99. {
  100. WX.ShareAppMessage(new ShareAppMessageOption()
  101. {
  102. title = "最强战力排行榜!谁是第一?",
  103. query = "minigame_action=show_group_list",
  104. imageUrl = "https://mmgame.qpic.cn/image/5f9144af9f0e32d50fb878e5256d669fa1ae6fdec77550849bfee137be995d18/0",
  105. });
  106. });
  107. ReportButton.onClick.AddListener(() =>
  108. {
  109. OpenDataMessage msgData = new OpenDataMessage();
  110. msgData.type = "setUserRecord";
  111. msgData.score = Random.Range(1, 1000);
  112. string msg = JsonUtility.ToJson(msgData);
  113. Debug.Log(msg);
  114. WX.GetOpenDataContext().PostMessage(msg);
  115. });
  116. }
  117. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/99833
推荐阅读
相关标签
  

闽ICP备14008679号