下載安裝Unity開發(fā)套件并運(yùn)行Demo

前言:

筆者近期在學(xué)習(xí) Unity 語(yǔ)言開發(fā),把 unity 開發(fā)工具的使用做一個(gè)整理歸檔,有興趣的小伙伴可以參考此文章 入門,這里以 “騰訊云即時(shí)通信 IM Unity uikit Demo”為用例,從工具安裝到跑通Demo 的整理流程梳理,希望能幫助下新手小伙伴,廢話不多說(shuō),現(xiàn)在開始~

申請(qǐng) unity 開發(fā)賬號(hào)并 下載 unity hub 開發(fā)套件:點(diǎn)擊下載

  1. 先申請(qǐng)賬號(hào)并登錄


  2. 下載 Unity Hub 工具(用于管理各個(gè)版本的 Unity Editer編輯器)


3.(可選操作)為了方便 Unity Hub使用,可以設(shè)置 Unity Hub 語(yǔ)言為 “中文”



  1. 安裝 Unity Editer 版本





  2. 下載 Unity API 和 Uikit Demo 并導(dǎo)入

  1. 打開項(xiàng)目預(yù)覽


  2. 使用 VS 打開配置文件


  • 填寫正確的 sdkappid(記得 ctrl + s 保存)


  1. 修改 Main.cs 為以下內(nèi)容 并設(shè)置 修改后的 userId 和 userSig(記得 ctrl + s 保存)


using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using Jing.ULiteWebView;
using UnityEngine.SceneManagement;
using com.tencent.imsdk.unity;
using System.Security.Cryptography;
// using UnityEditor.Compilation;

namespace Com.Tencent.IM.Unity.UIKit.Example
{
  public class Main : MonoBehaviour
  {
    public InputField phoneNumber;
    public InputField captcha;
    public Button getCaptchaButton;
    public Button loginButton;
    // public GameObject headerImg;
    private int totalTime = 60;
    private string sessionId;
    private IEnumerator countDownCoroutine;

    private void Start()
    {
      // StartCoroutine(DownTexture(Config.headerImgUrl, headerImg));
      // 設(shè)置表情包信息
      Core.SetStickerPackageList(Config.stickers);
      ChangeSystemLanguage();
      string userId = PlayerPrefs.GetString("userId");
      string sdkUserSig = PlayerPrefs.GetString("sdkUserSig");

      if (!string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(sdkUserSig))
      {
        Core.SetConfig(Config.sdkappid, userId, sdkUserSig);
        Core.Init();
        Core.Login(HandleAfterLogin);
      }

      getCaptchaButton.onClick.AddListener(GetCaptcha);
      loginButton.onClick.AddListener(Login);


      countDownCoroutine = CountDown();
      string storedPhone = PlayerPrefs.GetString("phone");

      if (!string.IsNullOrEmpty(storedPhone))
      {
        phoneNumber.text = storedPhone;
      }
    }

    private void ChangeSystemLanguage(){
      string language = GetSystemLanguageWrapper.GetSystemLanguage();
      Debug.Log("system language: "+language);
      switch (language){
        case "Chinese":
          LanguageDataManager.SetCurrentLanguageValue(Language.Chinese);
          break;
        default:
          LanguageDataManager.SetCurrentLanguageValue(Language.English);
          break;
      }
    }

    private IEnumerator DownTexture(string url, GameObject gameObject)
    {
      UnityWebRequest WebRequest = new UnityWebRequest(url);
      DownloadHandlerTexture Download = new DownloadHandlerTexture(true);
      WebRequest.downloadHandler = Download;
      yield return WebRequest.SendWebRequest();
      //等待資源下載完成
      while (!WebRequest.isDone)
      {
        yield return null;
      }
      if (string.IsNullOrEmpty(WebRequest.error))
      {
        //文件下載成功
        //讀取的圖片
        Texture2D rexture = Download.texture;
        gameObject.SetActive(true);
        gameObject.GetComponent<Image>().sprite = GetSpriteByTexture(rexture);
        // Debug.Log("圖片下載成功");
      }
      else
      {
        //文件下載失敗
        // Debug.Log("圖片下載失敗");
      }
    }
    //將texture轉(zhuǎn)成image的Sprite
    private Sprite GetSpriteByTexture(Texture2D tex)
    {
      Sprite _sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
      return _sprite;
    }

    private void Reset()
    {
      getCaptchaButton.interactable = true;
      totalTime = 60;
      getCaptchaButton.GetComponentInChildren<Text>().text = "獲取驗(yàn)證碼";
    }

    private IEnumerator CountDown()
    {
      Debug.Log("incountdown");
      Text buttonText = getCaptchaButton.GetComponentInChildren<Text>();
      getCaptchaButton.interactable = false;
      while (totalTime >= 0)
      {
        buttonText.text = totalTime.ToString();
        yield return new WaitForSeconds(1);
        totalTime--;
      }
      Reset();
    }

    private void GetCaptcha()
    {
      if (string.IsNullOrEmpty(phoneNumber.text))
      {
        return;
      }

      ULiteWebView.Ins.RegistJsInterfaceAction("messageHandler", GetCaptchaRes);
      ULiteWebView.Ins.RegistJsInterfaceAction("capClose", HandleCapClose);
      ULiteWebView.Ins.RegistJsInterfaceAction("getsize", getCaptchasize);
      var marginW = (UnityEngine.Screen.width - 768) / 2;
      var marginH = (UnityEngine.Screen.height - 768) / 2;
      ULiteWebView.Ins.Show(marginH, marginH, marginW, marginW);
      // ULiteWebView.Ins.Show();
      ULiteWebView.Ins.LoadLocal(Config.captchaUrl);
      // 倒計(jì)時(shí)
      Debug.LogError("marginW"+marginW);
      Debug.LogError("marginH" + marginH);
      IEnumerator countdowntry = CountDown();
      StartCoroutine(countdowntry);
    }
    private void getCaptchasize(string res){
      Debug.LogError("capchasize"+res);
    }
    private IEnumerator SMSRequest(string path, string dataStr, Action<string> cb)
    {
      byte[] postData = System.Text.Encoding.UTF8.GetBytes(dataStr);
      var url = Config.smsLoginHttpBase + path;

      var www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
      www.chunkedTransfer = false;
      www.uploadHandler = new UploadHandlerRaw(postData);
      www.downloadHandler = new DownloadHandlerBuffer();
      www.SetRequestHeader("Content-Type", "application/json");
      www.SetRequestHeader("Accept", "application/json");

      yield return www.SendWebRequest();

      if (www.isNetworkError || www.isHttpError)
      {
        Debug.Log(www.error);
      }
      else
      {
        // data.sessionId
        // Debug.Log("Form upload complete! " + path + www.downloadHandler.text);
        cb(www.downloadHandler.text);
      }
    }

    // 驗(yàn)證驗(yàn)證碼后臺(tái)下發(fā)短信
    private void VervifyPicture(MessageObj messageObj)
    {
      var data = new VerifyPictureReq
      {
        phone = "+86" + phoneNumber.text,
        ticket = messageObj.ticket,
        randstr = messageObj.randstr,
        appId = Config.sdkappid,
        apaasAppId = ""
      };

      StartCoroutine(SMSRequest("/base/v1/auth_users/user_verify_by_picture", Utils.ToJson(data), (string res) => HandleVerifyByPicture(res)));
    }

    private void HandleVerifyByPicture(string res)
    {
      var resObj = Utils.FromJson<SMSRes<VerifyResData>>(res);

      if (resObj.errorCode != 0)
      {
        Debug.LogError("Res Error: " + resObj.errorMessage);
        return;
      }

      sessionId = resObj.data.sessionId;
    }

    private void HandleLogin(string res)
    {
      //var resObj = Utils.FromJson<SMSRes<LoginResData>>(res);

      //if (resObj.errorCode != 0)
      //{
      //  Debug.LogError("Res Error: " + resObj.errorMessage);
      //  return;
      //}

      //      // Debug.LogError("11111111userID: " + resObj.data.userId);
      //      // Debug.LogError("11111111sdkUserSig: " + resObj.data.sdkUserSig);

      var userId = "";
      var userSig = "";

      PlayerPrefs.SetString("userId", userId);
      PlayerPrefs.SetString("sdkUserSig", userSig);
      
      Core.SetConfig(Config.sdkappid, userId, userSig);
      Core.Init();
      Core.Login(HandleAfterLogin);
    }

    private void HandleAfterLogin(params string[] args)
    {
      if (!Utils.IsCallbackLegit(args[0]))
      {
        PlayerPrefs.DeleteKey("userId");
        PlayerPrefs.DeleteKey("sdkUserSig");
        return;
      }
      StopCoroutine(countDownCoroutine);
      if (!string.IsNullOrEmpty(phoneNumber.text))
      {
        PlayerPrefs.SetString("phone", phoneNumber.text);
      }
      
      // 不用重復(fù)進(jìn)group
      TencentIMSDK.GroupJoin(Config.communityId, "Hello", (int code, string desc, string user_data) =>
      {
        Debug.Log("Joined " + Config.communityId);
      });
      TencentIMSDK.GroupJoin(Config.channelId, "Hello", (int code, string desc, string user_data) =>
      {
        Debug.Log("Joined " + Config.channelId);
      });
      TencentIMSDK.GroupJoin(Config.groupId, "Hello", (int code, string desc, string user_data) =>
      {
        Debug.Log("Joined " + Config.groupId);
      });
      
      Reset();
      SceneManager.LoadScene("Chat");
    }

    private void HandleCapClose(string res)
    {
      ULiteWebView.Ins.Close();
    }

    private void GetCaptchaRes(string res)
    {
      var msgObj = Utils.FromJson<MessageObj>(res);
      VervifyPicture(msgObj);
      ULiteWebView.Ins.Close();
    }

    private void Login()
    {
      //if (string.IsNullOrEmpty(phoneNumber.text) || string.IsNullOrEmpty(captcha.text) || string.IsNullOrEmpty(sessionId))
      //{
      //  return;
      //}

      //loginButton.interactable = false;

      //var data = new SMSLoginReq
      //{
      //  sessionId = sessionId,
      //  phone = "+86" + phoneNumber.text,
      //  code = captcha.text,
      //  apaasAppId = "",
      //  tag = "im"
      //};

      //StartCoroutine(SMSRequest("/base/v1/auth_users/user_login_code", Utils.ToJson(data), (string res) => HandleLogin(res)));
      //loginButton.interactable = true;

      HandleLogin("");
    }
    void OnApplicationQuit()
    {
      Core.Uninit();
    }
  }

  public class MessageObj
  {
    public string randstr;
    public string ticket;
  }

  public class VerifyPictureReq
  {
    public string phone;
    public string appId;
    public string ticket;
    public string randstr;
    public string apaasAppId;
  }

  public class SMSLoginReq
  {
    public string sessionId;
    public string phone;
    public string code;
    public string apaasAppId;
    public string tag;
  }

  public class SMSRes<T>
  {
    public int errorCode;
    public string codeStr;
    public string errorMessage;
    public T data;
  }

  public class LoginResData
  {
    public string userId;
    public int sdkAppId;
    public string sdkUserSig;
    public string token;
    public string expire;
    public string phone;
    public string email;
    public string name;
    public string avatar;
    public string apaasAppId;
    public string apaasUserId;

  }

  public class VerifyResData
  {
    public string sessionId;
  }
}
  1. 最后運(yùn)行項(xiàng)目


  • 運(yùn)行成功的效果


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容