使用Unity調用派樣機技術小結距離這個開發這個項目已經過去差不多兩年時間了,今天我閑來無事清理電腦里項目的時候無意看到了這個項目。已經都過去將近兩年時間了,時光荏苒啊!兩年前的自己也是一個沖動的年輕人,拼了命的做項目,現在想想自己,年輕人還是真年輕呀。算了,廢話不多說,今天在這里總結一下調用派樣機的開發流程。需求梳理當時公司讓實現一個什么樣的功能吶?就是在派樣機(類似于飲料自動購物機那種機器)上的電腦上,開發一款Unity程序,這款程序上有一個二維碼,用戶用微信掃一掃掃這個二維碼,這時用戶的手機上就會出現一個互動的小程序,用戶互動完成后,服務器判斷用戶互動完成,給派樣機的Unity程序發一個網絡指令。Unity程序收到該指令后,使用串口通信給派樣機發一個指令,派樣機硬件收到該指令后,即調用硬件推出一個小禮物,送給用戶。圖1使用的派樣機這個項目不是什么很復雜的項目,這里面有兩個難點。1.獲取服務器傳過來的信號,進行判斷。2.判斷完畢服務器的信號后,調用派樣機,調用硬件進行派樣。只要開發完成這兩個功能后,這個項目就算是完成了。開發步驟1.首先在Unity中創建UI,將二維碼貼在Unity的程序里的UI上,UI。圖2設計的程序UI2.開發獲取服務器指令功能,并且進行判斷,如果獲取到正確的信息,即對派樣機發送派樣指令,代碼如下。usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.Networking;usingNewtonsoft.Json;usingUnityEngine.UI;publicclassManagercomManager;//StartiscalledbeforethefirstframeupdatevoidStart(){callback+=dispchater;StartCoroutine(GetData(callback));}privatevoiddispchater(){//Debug.Log("掉小樣!");comManager.DemoMechinesendCom();}//加載路徑圖片IEnumeratorGetData(Actionaction)//Actionaction{while(true){yieldreturnnewWaitForSeconds(2.0f);UnityWebRequestunityWebRequest=UnityWebRequest.Get("Manager.csusingUnityEngine;usingSystem.Collections;usingSystem;usingSystem.Threading;usingSystem.Collections.Generic;usingSystem.IO.Ports;publicclassComManager:MonoBehavIoUr{//publicComManagerinstance;//端口號stringcom2="";privateSerialPortsp2;//波特率privateintbaudrate;publicfloattimer=0.1f;//privateboolisShinning=false;//配置文件管理類publicConfigTestconfigTest;//privatevoidAwake()//{//instance=this;//}voidStart(){//stringcom2="COM7";com2=configTest.dic["端口號"]["portName"];baudrate=int.Parse(configTest.dic["波特率"]["baudrate"]);//row=8;row=int.Parse(configTest.dic["參數"]["row"]);//column=4;column=int.Parse(configTest.dic["參數"]["column"]);//depth=5;depth=int.Parse(configTest.dic["參數"]["depth"]);mainCount=int.Parse(configTest.dic["參數"]["mainCount"]);StartCoroutine(StartCom());}IEnumeratorStartCom(){yieldreturnnewWaitForSeconds(0.1f);sp2=newSerialPort(com2,baudrate,Parity.None,8,StopBits.One);if(!sp2.IsOpen){sp2.open();}}//////派樣機串口//////privatevoidSendDemoMechineData(byte[]data){if(sp2.IsOpen){sp2.Write(data,data.Length);}}voidOndisable(){if(sp2.IsOpen){sp2.Close();}}privateintrow;//8privateintcolumn;//5privateintdepth;//10privateintmainCount=40;//總數privatestaticintindex=0;publicvoidDemoMechinesendCom(){inttempRow=index%row;//第幾個inttempColumn=(index/row)%row;//第幾行inttempdepth=index/(row*column)%depth;Debug.Log(index+"row:"+tempRow+"col:"+tempColumn+"depth"+tempdepth);stringpos=tempColumn.ToString("0")+tempRow.ToString("0");stringcorPos=System.Convert.ToString(int.Parse(pos),16).PadLeft(2,'0');stringdata="0105"+corPos+"030000000000000000000000000000";byte[]byteData=CRC.StringToHexByte(data);byte[]crcByteData=CRC.CRC16(byteData);//Debug.Log(CRC.BytetoString(crcByteData));data+=CRC.BytetoString(crcByteData);//Debug.Log(data);byte[]byteDatas=CRC.StringToHexByte(data);SendDemoMechineData(byteDatas);index++;if(index>=mainCount){index=0;}}}小結就這樣,派樣機的功能就基本開發完成了。雖然這個程序的功能十分簡單,但是用處很大,創作不易,如果喜歡文章,請點個贊。