Unity 3D# 常用脚本

自动返回+隐藏鼠标 方法一

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

public class GameReturn : MonoBehaviour {
    //判断屏幕是否有人在操作,无人操作时开始计时,n s后返回待机界面
    bool isExit = false;
    //计时器
    float timer = 0f;
    private float maxTime;
    public Transform Bg, SecondStageLayer;

    // Use this for initialization
    void Start () {
        maxTime = float.Parse(Configs.instance.LoadText("return", "timer"));
        //print(maxTime);
        //是否隐藏鼠标
        Cursor.visible = bool.Parse(Configs.instance.LoadText("hideMouse", "false/ture"));
       // print(Cursor.visible);
    }

    // Update is called once per frame
    void Update () {
        if(!Input.GetMouseButton(0) && Input.touchCount == 0)
        {
            timer += Time.deltaTime;
            if (timer > maxTime)
            {
                Bg.gameObject.SetActive(true);
                SecondStageLayer.gameObject.SetActive(true);
                UDPClientTwo.instance.SocketSend("return");

//  Invoke("FirstBtnEvent", 1f);

                isExit = false;
                timer = 0f;
            }
        }
        else
        {
            timer = 0f;
        }
    }

    private void FirstBtnEvent()
    {
        UDPClient.instance.SocketSend("FengHuangXinChun");
    }
}

自动返回+隐藏鼠标 方法二

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

public class GameReturn : MonoBehaviour
{
    //计时器
    float timer = 0f;
    private float maxTime;
    public Transform firstStageLayer, secondStageLayerZiRanZiYuan, ziRanStageLayer;
    // Use this for initialization

    Dictionary transStatusDic = new Dictionary();
    
    private void Awake()
    {
        //print(transform.name+"-=-=-==-");
        //Dictionary (transStatusDic);Transform(firstStageLayer);bool(firstStageLayer.gameObject.activeself)
        transStatusDic.Add(firstStageLayer, firstStageLayer.gameObject.activeSelf);                
        transStatusDic.Add(secondStageLayerZiRanZiYuan, secondStageLayerZiRanZiYuan.gameObject.activeSelf);
        transStatusDic.Add(ziRanStageLayer, ziRanStageLayer.gameObject.activeSelf);

    }


    void Start()
    {
        maxTime = int.Parse(Configs.instance.LoadText("return", "timer"));

        //是否隐藏鼠标
        Cursor.visible = bool.Parse(Configs.instance.LoadText("hideMouse", "false/ture"));
       // print(Cursor.visible);
    }

    bool isActive;
    void Update()
    {
        if (!Input.GetMouseButton(0) && Input.touchCount == 0)
        {
            timer += Time.deltaTime;
            if (timer > maxTime)
            {
                foreach (var item in transStatusDic)
                {
                    item.Key.gameObject.SetActive(item.Value);
                }

                timer = 0f;
            }
        }
        else
        {
            timer = 0f;
        }
    }
}

UDP 接收 发送

Config

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.Text;

/// 
/// 配置文件
/// 
public class Configs : MonoBehaviour {

    public static Configs instance;


    private void Awake()
    {
        instance = this;
        init();
    }

    private string[] keys;
    public   JsonData jsonData;

    //初始化json
    void init()
    {
        string filepath;


#if UNITY_EDITOR
        filepath =Application.dataPath + "/StreamingAssets" + "/Config.txt";
#elif UNITY_STANDALONE_WIN
                filepath =Application.dataPath + "/StreamingAssets" + "/Config.txt";
#elif UNITY_IPHONE
                filepath = Application.dataPath + "/Raw" + "/Config.txt";   
#elif UNITY_ANDROID
                filepath = "jar:Application.dataPath + "!/assets" + "/Config.txt";
#endif
        bool isContains = FileHandle.instance.isExistFile(filepath);

      

        //Debug.Log(isContains);
        if (isContains)
        {
            string str = FileHandle.instance.FileToString(filepath, Encoding.UTF8);
            Debug.Log(str);

            jsonData = JsonMapper.ToObject(str);
            #region  key 遍历
         
            //IDictionary dict = jsonData as IDictionary;

            //int count = 0;
            //keys = new string[dict.Count];
            //foreach (string key in dict.Keys)
            //{

            //    keys[count] = key;
            //    Debug.Log(keys[count]);
            //    count++;

            //}
             
            #endregion
        }
 
    }

 
    /// 
    /// 外部调用获取文字信息
    /// 
    /// 
    /// 
    /// 
   public string LoadText(string name,string info)
   {
        //Debug.Log("name = " + name + " info = " + info);
        string str = (string)jsonData[name][info];
        //Debug.Log(str);
        return str;
   }

    /// 
    /// 获取子节点个数
    /// 
    /// 
    public int GetJsonCount()
    {
        return jsonData.Count;
    }
    
    /// 
    /// 获取子节点下子节点个数
    /// 
    /// 
    /// 
    public int GetJsonCount(string name)
    {
        return jsonData[name].Count;
    }

}

FileHandle

using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Text;

/// 
/// 读取文件
/// 
public class FileHandle   {

    private FileHandle(){}
    public static readonly FileHandle instance = new FileHandle();

    //the filepath if there is a file
    public bool isExistFile(string filepath){
        return File.Exists(filepath);
    }

    public bool IsExistDirectory(string directorypath){
        return Directory.Exists(directorypath);
    }

    public bool Contains(string Path,string seachpattern){
        try{
            string[] fileNames = GetFilenNames(Path,seachpattern,false);
            return fileNames.Length!=0;
        }
        catch{
            return false;
        }
    }

    //return a file all rows
    public static int GetLineCount(string filepath){
        string[] rows = File.ReadAllLines(filepath);
        return rows.Length;
    }


    /// 
    /// 创建文件
    /// 
    /// 
    /// 
    public bool CreateFile(string filepath){
        try{
            if(!isExistFile(filepath)){
                StreamWriter sw;
                FileInfo file = new FileInfo(filepath);
                //FileStream fs = file.Create();
                //fs.Close();
                sw = file.CreateText();
                sw.Close();
            }
        }
        catch{
            return false;
        }
        return true;
    }

    public string[] GetFilenNames(string directorypath,string searchpattern,bool isSearchChild){
        if(!IsExistDirectory(directorypath)){
            throw new FileNotFoundException();
        }
        try{
            
            return Directory.GetFiles(directorypath,searchpattern,isSearchChild?SearchOption.AllDirectories:SearchOption.TopDirectoryOnly);
        }
        catch{
            return null;
        }

    }


    /// 
    /// 写入文件
    /// 
    /// 地址
    /// 内容
    public void WriteText(string filepath,string content)
    {
        //File.WriteAllText(filepath,content);
        FileStream fs = new FileStream(filepath,FileMode.Append);
        StreamWriter sw = new StreamWriter(fs,Encoding.UTF8);
        sw.WriteLine(content);
        sw.Close();
        fs.Close();
        Debug.Log("write: filepath: "+filepath);
        Debug.Log("write: content: "+content);
        Debug.Log("写入完毕");
    }

    public void AppendText(string filepath,string content){
        File.AppendAllText(filepath,content);
    }


    /// 
    ///  读取问字内容
    /// 
    /// 
    /// 
    /// 
    public string FileToString(string filepath,Encoding encoding){
        FileStream fs = new FileStream(filepath,FileMode.Open,FileAccess.Read);
        StreamReader reader = new StreamReader(fs,encoding);
        try{
            return reader.ReadToEnd();
        }
        catch{
            return string.Empty;
        }
        finally{
            fs.Close();
            reader.Close();
            //Debug.Log("读取完毕");
        }
    }


    /// 
    /// 删除文件
    /// 
    /// 
    public void ClearFile(string filepath){
         

        File.Delete(filepath);
        CreateFile(filepath);
    }

}

UDPClient 能接收能发送


using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.SceneManagement;
public class UDPClient : MonoBehaviour
{
    public static UDPClient instance;
    //服务端的IP
    string /*UDPServerIP*/UDPClientIPOne,UDPClientIPTwo,UDPLocalSeverIPOne;
    //目标socket 
    Socket socket;
    //服务端 
    EndPoint serverEnd;
    //服务端端口 
    //IPEndPoint ipEnd;
    //接收的字符串 
    string recvStr;
    //发送的字符串 
    string sendStr;
    //接收的数据,必须为字节 
    byte[] recvData = new byte[1024];
    //发送的数据,必须为字节 
    byte[] sendData = new byte[1024];
    //接收的数据长度 
    int recvLen = 0;

    List MsgPool;
    //连接线程
    Thread connectThread;

    bool isClientActive = false;


    int port;
    int /*localPort*/ UserPortOne, UserPortTwo ,LocalSeverPortOne;

    public delegate void  UDPClientDele(string ss);
    public event UDPClientDele UDPClientEvent;



    private void Awake()
    {
        instance = this;
    }

    void Start()
    {
        //UDPServerIP = Configs.instance.LoadText("LocalServerIP", "ip");//服务端的IP.自己更改
        //print(UDPServerIP);
        //localPort = int.Parse(Configs.instance.LoadText("LocalPort", "port"));

        UDPLocalSeverIPOne = Configs.instance.LoadText("LocalServerIPTwo", "ip");
        LocalSeverPortOne = int.Parse(Configs.instance.LoadText("LocalPortTwo", "port"));


        UDPClientIPOne = Configs.instance.LoadText("UserClientIPOne", "ip");
        UserPortOne = int.Parse(Configs.instance.LoadText("UserPortOne", "port"));

        UDPClientIPTwo = Configs.instance.LoadText("UserClientIPTwo", "ip");
        UserPortTwo = int.Parse(Configs.instance.LoadText("UserPortTwo", "port"));

        //UDPServerIP = UDPServerIP.Trim();
        isClientActive = true;
        InitSocket(); //在这里初始化
    }

    private void Update()
    {
        //if (Input.GetMouseButtonDown(0))
        //{
        //    SocketSend("12");
        //}

    }

    //初始化 
    void InitSocket()
    {
        //定义连接的服务器ip和端口,可以是本机ip,局域网,互联网 
        //ipEnd = new IPEndPoint(IPAddress.Parse(UDPServerIP), localPort);

        //定义套接字类型,在主线程中定义 
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      
        //定义服务端 
        IPEndPoint sender = new IPEndPoint(IPAddress.Parse(UDPLocalSeverIPOne), LocalSeverPortOne);

        serverEnd = (EndPoint)sender;
        socket.Bind(serverEnd);
        //建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息 
        //SocketSend("hello");
        //开始心跳监听
        //客户端发送心跳消息后,计时器开始计时,判断3秒内是否能收到服务端的反馈


        //开启一个线程连接,必须的,否则主线程卡死 
        connectThread = new Thread(new ThreadStart(SocketReceive));
        connectThread.Start();
    }

    //发送字符串
    public void SocketSend(string sendStr)
    {
        //清空发送缓存 
        sendData = new byte[1024];
        //数据类型转换 
        sendData = Encoding.UTF8.GetBytes(sendStr);
        //发送给指定服务端

        // 对方端口  两个端口
        socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne),UserPortOne));
        //socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo),UserPortTwo));
        //print(3333);
    }

    public void ButtonSend(string sendStr, string status)
    {
        //清空发送缓存 
        sendData = new byte[1024];
        //数据类型转换 
        sendData = Encoding.UTF8.GetBytes(sendStr);
        //发送给指定服务端


        if (status == "1")
        {
            socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne), UserPortOne));
        }

        else if (status == "2")
        {
            socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo), UserPortTwo));
        }


        else if (status == "3")
        {
            socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne), UserPortOne));
            socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo), UserPortTwo));
        }

        // 对方端口  两个端口

        //print(3333);

    }

    public void SocketSendTwo(string sendStr)
    {
        //清空发送缓存
        sendData = new byte[1024];

    }
    
    //接收服务器消息
    void SocketReceive()
    {
        //进入接收循环 
        while (isClientActive)
        {
            //对data清零 
            recvData = new byte[1024];
            try
            {
                //获取服务端端数据
                recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
                if (isClientActive == false)
                {
                    break;
                }
            }
            catch (Exception e)
            {
                print(e.Message);
            }
            //打印服务端信息 
            //输出接收到的数据 
            if (recvLen > 0)
            {
                //接收到的信息
                recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
                print(recvStr);
                if (UDPClientEvent!=null)
                {
                    UDPClientEvent(recvStr);
                    //print(recvStr);
                }
            }
            
        }
    }
    
    //连接关闭
    public void SocketQuit()
    {   
        //关闭线程
        if(connectThread != null)
        {
            isClientActive = false;
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
    }

    void OnApplicationQuit()
    {
        SocketQuit();
    } 
    

    void OnDisable()
    {
        isClientActive = false;
        SocketQuit();
        Thread.Sleep(25);
    }
}

接收相应的UDP消息执行相应的指令

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class VedioControl : MonoBehaviour {
    //判断是否有接收到返回的指令
    bool isExit = false;
    //计时器
    float timer = 0;
    private float maxTime = 600;


    public static VedioControl instance;
    public Transform title1, title2;
    public Transform Imagetitle, panel;
    //public Transform Imagetitle, panel;

    [HideInInspector]
    public bool IsPlaying = false;


    string udpmsg,receiveMessOne, receiveMessTwo,videoCutDownUI, videoCutDownTimer;
    bool isudpmsg = false;



    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        UDPClient.instance.UDPClientEvent += GetMessageFromUdpClient;
        receiveMessOne = Configs.instance.LoadText("receiveMessOne", "messageOne");   //视频结束所接收的消息
        receiveMessTwo = Configs.instance.LoadText("receiveMessTwo", "messageTwo");    //视频开始播放所接收的消息

       // videoCutDownUI = Configs.instance.LoadText("videoCutDownUI", "instruct");   //视频5分钟不定时播放
       // videoCutDownTimer = Configs.instance.LoadText("videoCutDownTimer", "instruct"); // 视频的倒计时播放

    }

    // Update is called once per frame
    void Update () {


        if(VedioControl.instance.IsPlaying == true)
        {
            timer += Time.deltaTime;
            if(timer > maxTime)
            {
                IsPlaying =false;

                isExit = false;
                timer = 0f;
            }
        }
        else
        {
            timer = 0f;
        }


        //接收指令执行相应的操作
        if (isudpmsg)
        {
            isudpmsg = false;
            if (udpmsg== receiveMessOne)
            {

                OnPreparePlaytitle1();
                print(receiveMessOne);
                print("111+++-----+++");
            }
            else if (udpmsg == receiveMessTwo)
            {
                OnPreparePlaytitle2();
                print("111+++-----+++");
            }
            //else if (udpmsg == videoCutDownUI)
            //{
            //    OnPreparePlaytitle3();
            //}
            //else if (udpmsg == videoCutDownTimer)
            //{
            //    OnPreparePlaytitle4();
            //}
        }
    }

    void GetMessageFromUdpClient(string ss) {

        udpmsg = ss;
        isudpmsg = true;

    }


    public void OnPreparePlaytitle1()
    {
            GameControl.instance.clickCount = 0;
            title1.gameObject.SetActive(true);
            title2.gameObject.SetActive(false);
            VedioControl.instance.IsPlaying = false;
    }


    public void OnPreparePlaytitle2()
    {
        print("112233");
        title1.gameObject.SetActive(false);
        title2.gameObject.SetActive(true);
        VedioControl.instance.IsPlaying = true;
    }


    //public void OnPreparePlaytitle3()
    //{
    //    Imagetitle.gameObject.SetActive(true);
    //    panel.gameObject.SetActive(false);
    //}


    //public void OnPreparePlaytitle4()
    //{
    //    timer += Time.deltaTime;
    //    if (timer >= 5)
    //    {
    //        Imagetitle.gameObject.SetActive(false);
    //        panel.gameObject.SetActive(true);
    //    }
    //    else
    //    {

    //    }
    //}



    private void OnDisable()
    {
        UDPClient.instance.UDPClientEvent -= GetMessageFromUdpClient;
    }


    //public void OnPlayingtitle2()
    //{
    //    if (VedioControl.instance.IsPlaying)
    //    {
    //        //title1.gameObject.SetActive(false);
    //        //title2.gameObject.SetActive(true);
    //    }
    // }
}

Loom

Loom的作用:Loom继承自MonoBehaviour,在Unity流程管理中Update方法下检查需要回调的Action进行加锁并回调,确保在主线程执行,回调序列本身又作为静态数据保存,在任意线程调用添加,简单轻量;只需在初始化时的主线程中调用一次

Loom.Initialize();
之后在任意场景任意线程均可调用
Loom.QueueOnMainThread(()=>{
});

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Threading;
using System.Linq;

public class Loom : MonoBehaviour
{
    public static int maxThreads = 8;
    static int numThreads;

    private static Loom _current;
    private int _count;
    public static Loom Current
    {
        get
        {
            Initialize();
            return _current;
        }
    }

    void Awake()
    {
        _current = this;
        initialized = true;
    }

    static bool initialized;

    static void Initialize()
    {
        if (!initialized)
        {

            if (!Application.isPlaying)
                return;
            initialized = true;
            var g = new GameObject("Loom");
            _current = g.AddComponent();
        }

    }

    private List _actions = new List();
    public struct DelayedQueueItem
    {
        public float time;
        public Action action;
    }
    private List _delayed = new List();

    List _currentDelayed = new List();

    public static void QueueOnMainThread(Action action)
    {
        QueueOnMainThread(action, 0f);
    }
    public static void QueueOnMainThread(Action action, float time)
    {
        if (time != 0)
        {
            lock (Current._delayed)
            {
                Current._delayed.Add(new DelayedQueueItem { time = Time.time + time, action = action });
            }
        }
        else
        {
            lock (Current._actions)
            {
                Current._actions.Add(action);
            }
        }
    }

    public static Thread RunAsync(Action a)
    {
        Initialize();
        while (numThreads >= maxThreads)
        {
            Thread.Sleep(1);
        }
        Interlocked.Increment(ref numThreads);
        ThreadPool.QueueUserWorkItem(RunAction, a);
        return null;
    }

    private static void RunAction(object action)
    {
        try
        {
            ((Action)action)();
        }
        catch
        {
        }
        finally
        {
            Interlocked.Decrement(ref numThreads);
        }

    }


    void OnDisable()
    {
        if (_current == this)
        {

            _current = null;
        }
    }
    
    List _currentActions = new List();

    // Update is called once per frame  
    void Update()
    {
        lock (_actions)
        {
            _currentActions.Clear();
            _currentActions.AddRange(_actions);
            _actions.Clear();
        }
        foreach (var a in _currentActions)
        {
            a();
        }
        lock (_delayed)
        {
            _currentDelayed.Clear();
            _currentDelayed.AddRange(_delayed.Where(d => d.time <= Time.time));
            foreach (var item in _currentDelayed)
                _delayed.Remove(item);
        }
        foreach (var delayed in _currentDelayed)
        {
            delayed.action();
        }
    }
}

使用Loom后的UDPClient接收发送

using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.SceneManagement;

public class UDPClient : MonoBehaviour
{
    public static UDPClient instance;
    //服务端的IP
    string /*UDPServerIP*/UDPClientIPOne,UDPClientIPTwo,UDPLocalSeverIPOne;
    //目标socket 
    Socket socket;
    //服务端 
    EndPoint serverEnd;
    //服务端端口 
    //IPEndPoint ipEnd;
    //接收的字符串 
    string recvStr;
    //发送的字符串 
    string sendStr;
    //接收的数据,必须为字节 
    byte[] recvData = new byte[1024];
    //发送的数据,必须为字节 
    byte[] sendData = new byte[1024];
    //接收的数据长度 
    int recvLen = 0;

    List MsgPool;
    //连接线程
    Thread connectThread;

    bool isClientActive = false;


    int port;
    int /*localPort*/ UserPortOne, UserPortTwo ,LocalSeverPortOne;



    public delegate void  UDPClientDele(string ss);
    public event UDPClientDele UDPClientEvent;



    private void Awake()
    {
        instance = this;
    }

    void Start()
    {
        //UDPServerIP = Configs.instance.LoadText("LocalServerIP", "ip");//服务端的IP.自己更改
        //print(UDPServerIP);
        //localPort = int.Parse(Configs.instance.LoadText("LocalPort", "port"));

        UDPLocalSeverIPOne = Configs.instance.LoadText("LocalServerIP", "ip");
        LocalSeverPortOne = int.Parse(Configs.instance.LoadText("LocalPort", "port"));


        UDPClientIPOne = Configs.instance.LoadText("UserClientIP", "ip");
        UserPortOne = int.Parse(Configs.instance.LoadText("UserPort", "port"));

        //UDPClientIPTwo = Configs.instance.LoadText("UserClientIPTwo", "ip");
        //UserPortTwo = int.Parse(Configs.instance.LoadText("UserPortTwo", "port"));

        //UDPServerIP = UDPServerIP.Trim();
        isClientActive = true;
        InitSocket(); //在这里初始化
    }

    private void Update()
    {
        //if (Input.GetMouseButtonDown(0))
        //{
        //    SocketSend("12");
        //}

    }

    //初始化 
    void InitSocket()
    {
        //定义连接的服务器ip和端口,可以是本机ip,局域网,互联网 
        //ipEnd = new IPEndPoint(IPAddress.Parse(UDPServerIP), localPort);

        //定义套接字类型,在主线程中定义 
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      
        //定义服务端 
        IPEndPoint sender = new IPEndPoint(IPAddress.Parse(UDPLocalSeverIPOne), LocalSeverPortOne);

        serverEnd = (EndPoint)sender;
        socket.Bind(serverEnd);
        //建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息 
        //SocketSend("hello");
        //开始心跳监听
        //客户端发送心跳消息后,计时器开始计时,判断3秒内是否能收到服务端的反馈

        Loom.RunAsync(()=> {

            //开启一个线程连接,必须的,否则主线程卡死 
            connectThread = new Thread(new ThreadStart(SocketReceive));
            connectThread.Start();
        });
        
    }

    //发送字符串
    public void SocketSend(string sendStr)
    {
        //清空发送缓存 
        sendData = new byte[1024];
        //数据类型转换 
        sendData = Encoding.UTF8.GetBytes(sendStr);
        //发送给指定服务端

        // 对方端口  两个端口
        socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne),UserPortOne));
        //socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo),UserPortTwo));
        //print(3333);
    }

    //public void ButtonSend(string sendStr, string status)
    //{
    //    //清空发送缓存 
    //    sendData = new byte[1024];
    //    //数据类型转换 
    //    sendData = Encoding.UTF8.GetBytes(sendStr);
    //    //发送给指定服务端


    //    socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne), UserPortOne));

    //    //if (status == "1")
    //    //{
    //    //    socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne), UserPortOne));
    //    //}

    //    //else if (status == "2")
    //    //{
    //    //    socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo), UserPortTwo));
    //    //}


    //    //else if (status == "3")
    //    //{
    //    //    socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne), UserPortOne));
    //    //    socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo), UserPortTwo));
    //    //}

    //    // 对方端口  两个端口

    //    //print(3333);

    //}

    public void SocketSendTwo(string sendStr)
    {
        //清空发送缓存
        sendData = new byte[1024];

    }
    
    //接收服务器消息
    void SocketReceive()
    {
        //进入接收循环 
        while (isClientActive)
        {
            //对data清零 
            recvData = new byte[1024];
            try
            {
                //获取服务端端数据
                recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
                if (isClientActive == false)
                {
                    break;
                }
            }
            catch (Exception e)
            {
                print(e.Message);
            }
            //打印服务端信息 
            //输出接收到的数据 
            if (recvLen > 0)
            {
                //接收到的信息
                recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
                //print(recvStr);
                
                Loom.QueueOnMainThread(()=> {
                    if (UDPClientEvent != null)
                    {
                        UDPClientEvent(recvStr);
                        print(recvStr);
                        //print("开始连接");
                    }
                });

                
            }
            
        }
    }
    
    //连接关闭
    public void SocketQuit()
    {   
        //关闭线程
        if(connectThread != null)
        {
            isClientActive = false;
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
    }

    void OnApplicationQuit()
    {
        SocketQuit();
    } 
    

    void OnDisable()
    {
        isClientActive = false;
        SocketQuit();
        Thread.Sleep(25);
    }
    
}

使用Loom后的UDP 接收指令执行操作

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class ReceiveMessUDP : MonoBehaviour {

    public static ReceiveMessUDP instance;


    public Transform BgImg, SecondStageLayer, Special;


    //圆圈  和背景图层
    public GameObject Amplification, Bg;



    private void Awake()
    {
        instance = this;
    }


    // Use this for initialization
    void Start() {
        UDPClient.instance.UDPClientEvent += GetMessageFromUDPClient;
    }



    // Update is called once per frame
    void Update() {
       
    }

    void GetMessageFromUDPClient(string UdpMsg)
    {
        if (UdpMsg == "begin")
        {
            BgImg.gameObject.SetActive(false);
            SecondStageLayer.gameObject.SetActive(true);

            Invoke("FengHuangXinChun", 0f);
        }

        if (UdpMsg == "return")
        {
            BgImg.gameObject.SetActive(true);
            SecondStageLayer.gameObject.SetActive(true);

            UDPClient.instance.SocketSend("FengHuangXinChun");

            Invoke("FengHuangXinChun", 0f);
        }


        if (UdpMsg == "MoXingling")
        {

            OpenSpecial();

            //Invoke("UGUISprite", 0.5f);

            Invoke("closeSpecial", 0.5f);
            Invoke("MoXingling", 0.5f);
        }
        
        if (UdpMsg == "GuangZhouZhan")
        {
            OpenSpecial();

            Invoke("closeSpecial", 0.5f);
            Invoke("GuangZhouZhan", 0.5f);
        }
    }




    private void OnDisable()
    {
        UDPClient.instance.UDPClientEvent -= GetMessageFromUDPClient;
    }



    void ReceiveBgMsg()
    {
        SecondStageLayer.gameObject.SetActive(true);
        BgImg.gameObject.SetActive(false);
    }

    void OpenSpecial()
    {
        Special.gameObject.SetActive(true);
        //UGUISpriteAnimation.instance.Rewind();
        //Invoke("UGUISprite",0.6f);
 
    }
    void closeSpecial()
    {
        Special.gameObject.SetActive(false);

        //UGUISpriteAnimation.instance.Resume();
        //UGUISpriteAnimation.instance.IsPlaying = true;
        //print("0.5");

    }
    

    void UGUISprite()
    {

        //UGUISpriteAnimation.instance.Resume();

    }

    #region 背景和放大镜的坐标
    /// 
    /// Bg背景的坐标
    /// 
    /// 
    void SetBGPosition(Vector3 Pos)
    {

        float x = Pos.x;
        float y = Pos.y;
        Bg.transform.localPosition = new Vector3(-x * 1.27f, -y * 1.65f, Bg.transform.localPosition.z);
    }

   

    Tween tween;
    void MoXingling()
    {
       // tween = DOTween.To(() => Bg.transform.localPosition, r => Bg.transform.localPosition = r, new Vector3(864, -1, 0), 0f);
        Amplification.transform.localPosition = new Vector3(76, 328,0);
        //  Bg.transform.localPosition = new Vector3(864, -1, 0);
        SetBGPosition(Amplification.transform.localPosition);
    }


    void GuangZhouZhan()
    {
        Amplification.transform.localPosition = new Vector2(-369, 144);

        SetBGPosition(Amplification.transform.localPosition);
    }

    #endregion
}

你可能感兴趣的:(Unity 3D# 常用脚本)