跳至主要內容

Unity

LiCheng大约 4 分钟

Unity

工具

  • json序列化库导入!
  • com.unity.nuget.newtonsoft-json

子物体自适应高度布局滚动

Unity版本自动构建🪲

脚本

// 詹姆斯·德夫为原创剧本灵感 原项目地址: https://github.com/JesusLuvsYooh/BuildVersionProcessor
// 例如,此文件必须位于“编辑器”文件夹(Unity/Assets/Editor)中。
// 将此类 autoBuildVersion  属性设置为 false,以禁用自动版本更改
// 在 "File/Manually Increment Build Version" 中文则是 "文件/Manually Increment Build Version" 手动生成版本
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
class BuildVersionProcessor : IPreprocessBuildWithReport{
    private readonly bool autoBuildVersion = true;

    public int callbackOrder => 0;

    public void OnPreprocessBuild(BuildReport report){
        //Debug.Log("MyCustomBuildProcessor.OnPreprocessBuild for target " + report.summary.platform + " at path " + report.summary.outputPath);
        if (autoBuildVersion){
            IncrementVersion();
        }
    }

    [MenuItem("File/Manually Increment Build Version", priority = 1)]
    public static void ButtonIncrementVersion(){
        Debug.Log("Button Increment Version called.");
        IncrementVersion();
    }

    private static void IncrementVersion(){
        string versionCurrent = Application.version;
        string[] versionParts = versionCurrent.Split('.');
        if (versionParts != null && versionParts.Length > 0){
            int versionIncremented = int.Parse(versionParts[^1]);
            versionIncremented += 1;
            versionParts[^1] = versionIncremented.ToString();
            PlayerSettings.bundleVersion = string.Join(".", versionParts);
            Debug.Log("Version:  " + versionCurrent + "  increased to:  " + PlayerSettings.bundleVersion);
        }else{
            Debug.Log("Version has no data, check Unity - Player Settings - Version, input box at top.");
        }
    }
}

Unity基础🪲

闭包🎈

闭包

  • 吐槽网上一堆垃圾教程没有一个解释好的,还不如编辑器提示的闭包类好
  • 无参和有参闭包
public static void GetAllPlayerList(Action handler){
        handler();
}

public static void GetAllPlayerList(Action<GoodsList> handler){
     handler(list);
}

协程🎈

提示

协程

IEnumerator Test(){ 
    //你的代码
    yield return null;
}

提示

延迟循环协程

IEnumerator Text(){ 
    while (true){
        // 之前代码
        yield return new WaitForSeconds (5);
        // 之后代码
    }
}

提示

延迟协程

IEnumerator Text(){ 
    yield return new WaitForSeconds (5);
    // 之后代码
}
  • 使用
StartCoroutine(Text());

ads接入🎈

  • https://docs.unity.com/ads/UnityAdsHome.html

小程序🏧

  • https://q.qq.com/
  • https://mp.weixin.qq.com/

json转换问题😄

[Serializable]
public class R<T>{
    /** 类型由SocketEnum觉得 */
    public string type;
    /** 必须改成string才能json转换成功 */
    public T data;
}

提示

T必须是设定好类型,如果T是string那么无法接受对象类型字符串

插件🐔

  • unity广告插件

DoTween🐷

EasySave🗾

LeanTouch💔

开源库🍏

WebSocket🍎

Protobuf😎

KCP🍇

LuBan👊

微信游戏🪲

UnityApi🐯

移动相关👊

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {
    // 速度
    public float speed = 5;

    // 一个基础的脚本移动
    private float moveX;
    private float moveY;
    private float jump;

    void Update() {
        moveY = Input.GetAxisRaw("Horizontal") * speed;
        moveY = Input.GetAxisRaw("Vertical") * speed;
        jump = Input.GetAxisRaw("Jump");
    }
}

邮件发送💒

private void SendMail(string title,string boyd) {
    SmtpClient mailClient = new SmtpClient("smtp.qq.com");
    mailClient.EnableSsl = true;
    //Credentials登陆SMTP服务器的身份验证.
    mailClient.Credentials = new NetworkCredential("你的邮箱", "授权码");
    //test@qq.com发件人地址、test@tom.com收件人地址
    MailMessage message = new MailMessage(new MailAddress("发件人邮箱"), new MailAddress("收件人邮箱"));
    // message.Bcc.Add(new MailAddress("tst@qq.com")); //可以添加多个收件人
    message.Body = boyd;//邮件内容
    message.Subject = title;//邮件主题
    mailClient.Send(message);
}

IoGameUnity✋

  • WebSocket
using System;
using System.Collections;
using System.Collections.Generic;
using Google.Protobuf;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityWebSocket;

/// <summary>
/// socket可以和 ExternalMessage 类进行捆绑使用
/// </summary>
public class SocketClient : MonoBehaviour{

    [Header("退出游戏面板")]
    public GameObject quitGamePanel;

    public static SocketClient v;
    public static readonly string address = "ws://192.168.1.3:10100/websocket";
    private static WebSocket socket;
    private void Awake(){
        if (v != null){
            Destroy(gameObject);
            return;
        }
        v = this;
        Connect();
        DontDestroyOnLoad(this);
        //注册函数 
        Init();
        StartCoroutine(TryConnect());
    }

    private void Init(){ //注册回调
        UserAction.Init();
        ChatAction.Init();
        GameAction.Init();
        HeroAction.Init();
    }

    IEnumerator TryConnect(){ //尝试重新链接
        while (true){
            yield return new WaitForSeconds (5);
            if (socket.ReadyState != WebSocketState.Open){
                Connect();
            }
        }
    }

    public void QuitGame(){
        socket.CloseAsync();
        Application.Quit();
    }

    private void Update(){
        if (Input.GetKeyDown(KeyCode.Escape) ){
            quitGamePanel.SetActive(true);
            AnimationUtil.DoScaleAnim(quitGamePanel.transform.GetChild(0).gameObject);
        }
    }

    private static void OnError(object sender, ErrorEventArgs e){//异常回调

    }
    private static void OnMessage(object sender, MessageEventArgs e){ //消息回调
        if (e.IsBinary){
            HandleManager.ParseMessage(e.RawData);
        }
    }
    private static void OnClose(object sender, CloseEventArgs e){//关闭回调

    }
    private static void OnOpen(object sender, OpenEventArgs e){//打开回调
        Debug.Log("链接服务器成功!");
    }

    /** m里面做了null判断 */
    public static void Send(int cmd, int subCmd, IMessage m = null){//发送数据
        socket.SendAsync(HandleManager.BuildMessage(cmd, subCmd, m));
    }

    public static void Connect(){
        socket = new WebSocket(address);
        // 注册回调
        socket.OnOpen += OnOpen;
        socket.OnClose += OnClose;
        socket.OnMessage += OnMessage;
        socket.OnError += OnError;
        socket.ConnectAsync();
    }
}
  • HandleManager
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Google.Protobuf;
using UnityEngine;

/// <summary>
/// 一个通用项目对象,
/// </summary>
public static class HandleManager{ //回调处理
    //---------------------------发送处理
    private static readonly Dictionary< int ,  EventHandler<Execute> > handlers = new();
    public  class Execute : EventArgs{    // 事件参数
        /** 状态码 */
        public readonly int responseStatus;
        /** 返回数据 */
        public readonly ByteString data;
        internal Execute(ByteString data,int responseStatus){
            this.data = data;
            this.responseStatus = responseStatus;
        }
    }
    public static void AddHandler(int cmd,int subCmd,  EventHandler<Execute> IHandler){  // 注册回调
        handlers.Add(GetMergeCmd(cmd,subCmd),IHandler); 
    }

    private static void PackageHandler( int mergeCmd, ExternalMessage data ) {  //分发消息
        try{
            EventHandler<Execute> handler = handlers[mergeCmd]; //对于路由不存在的错误处理
            if (handler != null) handler.Invoke(handler, new Execute(data.DataContent,data.ResponseStatus));
        }
        catch (Exception e){
            Debug.Log("不存在的路由: "+GetCmd(data.CmdMerge)+"-"+GetSubCmd(data.CmdMerge));
            Console.WriteLine(e);
            throw;
        }
    }
    public static void ParseMessage(byte[] bytes){ //解析消息
        ExternalMessage message = new ExternalMessage();
        message.MergeFrom(bytes);
        //Debug.Log(message);
        PackageHandler(message.CmdMerge,message);
    }

    //---------------------------路由命令处理
    public static int GetCmd(int merge) {//获取cmd
        return merge >> 16;
    }
    public static int GetSubCmd(int merge) {//获取subCmd
        return merge & 0xFFFF;
    }
    public static int GetMergeCmd(int cmd, int subCmd) {  //获取mergeCmd
        return (cmd << 16) + subCmd;
    }

    //---------------------------封装发送结果处理
    public static byte[] BuildMessage(int cmd,int subCmd,IMessage v = null){ // 封装消息发送
        ByteString data = ByteString.Empty;
        if (v != null){
            data = v.ToByteString();
        }
        var message = new ExternalMessage{
            CmdMerge = GetMergeCmd(cmd, subCmd),
            DataContent = data,
            ProtocolSwitch = 0,
            CmdCode = 1
        };
        return message.ToByteArray();
    }
}