banner
navBar home resume scripting
progNavBar Programming CPP
Game/Program:
"Unity Battle Space" Unity 3D client and Windows App Server
 

This was the beginnings of a project to have a Unity3D client work in unison with a VBS client using a server(TCP/IP winapp).

The Unity3D client is the internal model of the Leopard 2A4 tank written in C# and JS. The functionalities I made are all in C#. I dumped the JS into the Plugins folder so that my C# scripts could interact with them.

The Unity3D client mimics the hull rotation, turret rotation, and turret elevation of the VBS client's tank. When the user does the elevation/rotation themselves, the VBS client mimics the Uniy3D client's rotations/elevation. The user can turn stabilization on and off. With it on the turret will stay where the gunner is aiming. With it off, the turret will turn relative to the hull. The user can switch between the COAX gun and the Main Cannon. When the Unity3D client fires, so does the VBS client.

The stabilization functionality (as well as any non-mentioned functionality) was never completed/implemented due to my getting hired at Telos Entertainment. Right now the stabilization only effects the turret rotation but ignores the elevation. So I'd imagine when the DND gets a new batch of interns(I was the only programmer) someone will pick up where I left off.

The WinApp server was written in C#. I didn't remember to grab a screen shot and since I no longer work for the DND, it's impossible for me to obtain one. I do at least have some code samples.

The VBS plugin DLL was written in C++ so information about it can be found HERE in the C++ section.

 
Unity3D - client:
networkComs.cs
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

public class networkComs : MonoBehaviour 
{
    // Use this for initialization
    void Start () 
    {
    
    }
    
    void FixedUpdate () 
    {
        if (csStatics.bVBSupdate) //if there's an update for vbs
        {        
            TcpClient tcpclnt=new TcpClient(); //instantiate a tcp client
            //Debug.Log("Connecting...");
            
            try
            {
                tcpclnt.Connect("127.0.0.1", 8001); //connect at specified ip and port                                
    
                //Debug.Log("Connected");
                    
                Stream stm = tcpclnt.GetStream(); //grab a free stream

                ASCIIEncoding asen = new ASCIIEncoding(); //instantiate an ascii encoding object
                byte[] ba = asen.GetBytes(csStatics.strVBSupdate); //create a byte array and place user input into it as bytes
                //Debug.Log("Transmitting.....");

                stm.Write(ba, 0, ba.Length); //send data

                byte[] bb = new byte[csStatics.BUFFER_SIZE]; //create a byte array to receive data from server
                int k = stm.Read(bb, 0, (int)csStatics.BUFFER_SIZE); //place received data into the array (Read() returns an int)
                
                string receivedMessage=""; //holds received message
                string newHullRot=""; //holds vbs hull rot as string
                for (int i = 0; i < k; i++)
                {
                    receivedMessage+=Convert.ToChar(bb[i]); //feed received date into the string                    
                    if (i>=49) {newHullRot+=Convert.ToChar(bb[i]);} //grab new vbs hull rot
                }
                //Debug.Log(receivedMessage);
                csStatics.vbsHullRot=(float)Convert.ToDecimal(newHullRot);
                //Debug.Log(newHullRot);
                
                tcpclnt.Close(); //disconnect
            }                
            catch (Exception e) 
            { 
                //Debug.Log(" "+e.Message+"\n"+e.StackTrace);
            }
            
            csStatics.bVBSupdate=false; //lower vbs update flag
        }
    }
}
csStatics.cs
using UnityEngine;
using System.Collections;

[System.Serializable]
public class csStatics : MonoBehaviour 
{
    //networking///////////////////////////////////////////////////////
    public static uint BUFFER_SIZE; //size of command buffer
    public static bool bVBSupdate; //is there an update for vbs?
    public static string strVBSupdate; //vbs update command
    public static float curTurretRot; //current rotation of turret
    public static float prevTurretRot; //previous rotation of turret
    public static float curTurretElev; //current turret elevation
    public static float prevTurretElev; //previous turret elevation
    public static bool bFire; //are we firing?
    public static float tMainFireWait; //time since main was fired last
    public static bool bMain; //are we using the main or coax?
    public static float bJoyFire; //is the user firing with the jstick?
    public static bool bStab; //is stab on?
    public static float vbsHullRot; //vbs hull rot
    public static float tVBShullUpdate; //time since last vbs hull update
    public static Transform unityHullRot; //rotation of unity hull
    public static float tVBSturretUpdate; //time since we last updated the vbs turret rot
    public static Transform turretIndicator; //handle to turret rotation needle
    public static Transform stabOnTurretParent; //handle to turret's parent when stab is on
    public static Transform turretRotBox; //handle to turret's rot box
    public static float stabOffset; //offset for switching stab on/off
    public static bool bCanFireMain; //can we fire main
    ///////////////////////////////////////////////////////
    
    //leo2-multi///////////////////////////////////////////////////////
    public static bool bGunAt6; //is the turret pointing at 6 o'clock?
    public static string[] textList; //list of display strings
    public static uint curText; //which indicy are we at in the text list
    public static Vector3[] camLocs; //list of camera locations
    public static string verNum; //version number
    public static int points; //player's points
    public static float missionTimer; //how long is the user taking?
    public static bool bTimerOn; //is the timer counting?
    public static bool bWalkthroughFinished; //has the user completed the tutorial?
    public static uint TestMode; //are we in test mode? (reason for uint is so the initial value doesn't matter as this value must remain the
                                 //same when level is reloaded. So when in test mode a value of 12345 is assigned, all other vals mean we're
                                 //doing the walkthru
    public static bool bLaserOn; //is the laser on?
    public static bool bE00on; //is E00 on?
    public static string curChat; //current text in chat box
    public static bool bVisualScore; //should we display a point increase/decrease?
    public static string visualScore; //most recent text for score increment/decrement
    public static bool bScoreIncrement; //are we incrementing score?
    public static bool bIntro; //are we displaying intro text?
    ///////////////////////////////////////////////////////
    
    //componentFind///////////////////////////////////////////////////////
    public static bool mouseClicked; //did the user click the mouse?
    ///////////////////////////////////////////////////////
    
    //used in multiple scenes///////////////////////////////////////////////////////
    [SerializeField]
    private static Texture guiBG;
    ///////////////////////////////////////////////////////
    //used to identify position of camera///
    protected static Transform CommanderLocation;
    protected static Transform GunnerLocation;
    protected static Transform LoaderLocation;
    protected static Transform LowLoaderLocation;
    protected static Transform DriverLocation;
    
    // Use this for initialization
    void Start () 
    {
        //Setting the current postion of each location
        CommanderLocation=GameObject.Find("CommanderLocation").transform;
        GunnerLocation=GameObject.Find("GunnerLocation").transform;
        LoaderLocation=GameObject.Find("LoaderLocation").transform;
        LowLoaderLocation=GameObject.Find("LowLoaderLocation").transform;
        DriverLocation=GameObject.Find("DriverLocation").transform;
        //leo2-multi///////////////////////////////////////////////////////
        bGunAt6=false; //turret begins at 12 o'clock
        
        curText=0; //start with the first string
        //init strings
        textList=new string[]
        {    
            "Gunner, set turret to observe and wait for the light to stop flashing.\n(Located on the Operating Stage Control Panel)", 
            "Loader, set E-GSS to on.\n(Located on the Loader Control Box)",               
            "Gunner, turn on the Laser.\n(Located on the Computer Control Display Panel)", 
            "Gunner, turn on \"E00\".\n(Located on the Gunners Control Handle)", 
            "Gunner, set thermal to standby and wait for ready light to stop flashing.\n(Located on the Gunners Control and Display Panel)", 
            "Gunner, set thermal to on.\n(Located on the Gunners Control and Display Panel)", 
              "Gunner, switch the coax to main.\n(Located on the Gunners Control and Display Panel)", 
            "Complete!"
        };
        
        points=0; //start off with no points
        missionTimer=0.0f; //start timer at 0
        if (csStatics.TestMode!=12345) {csStatics.bTimerOn=false;} //don't use timer in walkthrough
        else {csStatics.bTimerOn=true;}
        
        bWalkthroughFinished=false; //the user hasn't even started the walkthrough, let alone completed it
        bLaserOn=false; //start off with laser off
        bE00on=false; //start off with e00 off
        curChat=" "; //init chat box
        bVisualScore=false; //no points have been earned/awarded yet, so why be visible?
        visualScore=" "; //nothing to show yet
        bScoreIncrement=true; //assume we're incrementing for now
        bIntro=true; //show intro before user begins
        ///////////////////////////////////////////////////////        
        
        //componentFind///////////////////////////////////////////////////////
        mouseClicked=false; //it's impossible to have clicked the mouse at this time
        ///////////////////////////////////////////////////////
        
        //used in multiple scenes///////////////////////////////////////////////////////
            
        ///////////////////////////////////////////////////////
        
        //networking///////////////////////////////////////////////////////
        BUFFER_SIZE=512; //set buffer size
        bVBSupdate=false; //start off with no updates for vbs
        strVBSupdate=""; //..
        curTurretRot=GunnerControlHandle.aimDegreeX; //grab current rotation
        prevTurretRot=curTurretRot; //there isn't a previous yet
        curTurretElev=GunnerControlHandle.aimDegreeY; //grab current turret elevation
        prevTurretElev=curTurretElev; //there isn't a previous yet
        bFire=false; //start off not firing
        tMainFireWait=5.0f; //the delay time is 5.0, so this will allow the cannon to be fired imediately
        bMain=false; //using coax by default
        bJoyFire=0.0f; //start off not firing
        bStab=false; //start with stab off
        vbsHullRot=0.0f; //vbs hull rot starts at 0 anyway
        tVBShullUpdate=0.2f; //set time since last vbs hull update beyond the limit so it the first time it executes right away
        unityHullRot=GameObject.Find("HullRott").transform; //set handle to unity hull rotation transform
        tVBSturretUpdate=0.2f; //we haven't sent this yet so assume enough time has passed
        turretIndicator=GameObject.Find("Turret Position Indactor").transform; //set handle to turret rotation indicator
        stabOnTurretParent=GameObject.Find("Leo_Tank_Multi_Scene").transform; //set handle to turret's parent when stab is on
        turretRotBox=GameObject.Find("TurretRott").transform; //set handle to turret's rot box
        stabOffset=unityHullRot.rotation.eulerAngles.y-turretRotBox.rotation.eulerAngles.y; //initial stab offset
        bCanFireMain=true; //we just started, we can totally fire
        
        Time.fixedDeltaTime=0.0085f; //minimum frequency physics updates
        ///////////////////////////////////////////////////////
        
        verNum="BUILD.0.8.C"; //set version number    (i bumped this up one letter for the build that talks to vbs) (IITSEC build was 0.8.B)
    }
    
    // Update is called once per frame
    void Update () 
    {        
        
        //init camera locations
        camLocs=new Vector3[]
        {
            CommanderLocation.transform.position,
            GunnerLocation.transform.position,
            LoaderLocation.transform.position,
            LowLoaderLocation.transform.position
            
            
        };
        tMainFireWait+=Time.deltaTime; //update time since last time main was fired
        tVBShullUpdate+=Time.deltaTime; //update time since last vbs hull update
        
        //check inputs
        if (Input.GetMouseButtonUp(0)) {mouseClicked=true;}
        else {mouseClicked=false;}
        
        bFire=Input.GetKey(KeyCode.Space); //fire button
        bJoyFire=Input.GetAxis("Fire3"); //jstick fire button        
        if (bJoyFire==0.0f && !bCanFireMain) {bCanFireMain=true;} //check if it's ok to send another fire command
        
        //update current weapon
        if (gunSwitch01.gunSwitch1selection=="main gun" && !bMain) {bMain=true;}
        else if (gunSwitch01.gunSwitch1selection=="coax" && bMain) {bMain=false;}
        
        //update stab
        if (!bStab && CCU_Knob.CCUKnobSelection=="Stab On") //if stab is false but we're set to stab
        {
            //turretRotBox.parent=stabOnTurretParent; //child turret to it's stab on parent
            
            bStab=true; //stab becomes true
            hull.stab = false;
            bVBSupdate=true; //put up vbs update flag
            strVBSupdate="SERVER set stab on"; //set command for server
        }
        else if (bStab && CCU_Knob.CCUKnobSelection!="Stab On") //if stab is true but we're not set to stab
        {
            //turretRotBox.parent=unityHullRot; //child turret to hull
            
            bStab=false; //stab becomes false
            hull.stab = true;
            bVBSupdate=true; //raise vbs update flag.
            strVBSupdate="SERVER set stab off"; //set command for server
        }
        
        //grab vbs hull rot
        if (!bVBSupdate && tVBShullUpdate>0.01f)
        {
            bVBSupdate=true; //raise vbs update flag
            strVBSupdate="SERVER get hullRot"; //set command
            tVBShullUpdate=0.0f; //reset time since last vbs hull update
        }
        
        //update turret indicator with offset (stab on)
        turretIndicator.transform.localRotation = Quaternion.Lerp(turretIndicator.transform.localRotation,                                                                   
                                                                      Quaternion.Euler(turretIndicator.localRotation.eulerAngles.x, 
                                                                                       turretIndicator.localRotation.eulerAngles.y, 
                                                                                       hull.aimDegreeY-hull.hullRotation),
                                                                      Time.deltaTime * 50.0f);
        //string[] temp=Input.GetJoystickNames();        
        //Debug.Log(Input.GetButton("joystick button 1"));
        //Debug.Log(Input.GetAxis("Fire1"));
        //Debug.Log(csStatics.bStab);
        //Debug.Log(vbsHullRot);
        //Debug.Log("VBS hull rot: "+vbsHullRot+" unity hull rot: "+unityHullRot.rotation.eulerAngles.y);
    }
    
    void FixedUpdate ()
    {
        hull.hullRotation= vbsHullRot;
        curTurretRot=hull.aimDegreeY; //update current turret rotation
        curTurretElev=GunnerControlHandle.aimDegreeY; //update current turret elevation    
        
        stabOffset=curTurretRot-unityHullRot.rotation.eulerAngles.y; //update stab offset
        //turretRotBox.rotation=Quaternion.Euler(turretRotBox.rotation.eulerAngles.x, GunnerControlHandle.aimDegreeX, turretRotBox.rotation.eulerAngles.z);        
        
        tVBSturretUpdate+=Time.fixedDeltaTime; //increment time since last vbs turrrt update
        
        if (bMain && (bFire || bJoyFire==1.0f) && tMainFireWait>=0.015f && bCanFireMain) //if the user fired main and enough time has passed since the previous firing
        {
            bVBSupdate=true; //put up the vbs update flag
            strVBSupdate="VBS fire main"; //set command to be sent to vbs
            tMainFireWait=0.0f; //reset firing delay
            bCanFireMain = false;
        }
        
        if (!bMain && (bFire || bJoyFire==1.0f) && tMainFireWait>=0.015f) //if the user is firing and coax is selected
        {
            bVBSupdate=true; //put up the vbs update flag
            strVBSupdate="VBS fire coax"; //set command to be sent to vbs
            tMainFireWait=0.0f;
        }        
        
        //if previous turret rotation or elavation is not the same as the current and there's not already a command to be sent
        if (!bVBSupdate && tVBSturretUpdate>=0.04f)// && (prevTurretRot!=curTurretRot || prevTurretElev!=curTurretElev))
        {
            bVBSupdate=true; //put up the vbs update flag            
            strVBSupdate="SERVER set turret rot "+hull.aimDegreeY.ToString()+", "+curTurretElev.ToString(); //set server command string
            
            prevTurretRot=curTurretRot; //update previous turret rotation
            prevTurretElev=curTurretElev; //update previous turret elevation
            tVBSturretUpdate=0.0f; //reset time since last vbs turret update
        }        
    }
}
 
Windows Application - server
frmServer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net; //networking
using System.Net.Sockets; //
using System.Threading;
using System.Diagnostics;
using System.ComponentModel;
using System.IO;

namespace testServer5_ConsoleToUsToUnity
{
    public partial class frmServer : Form
    {
        protected inputFlags input; //input flags        

        //thread lockers
        protected static readonly object consoleLocker=new object();
        protected static readonly object unityLocker = new object();
        protected static readonly object mainLocker = new object();
        protected static readonly object vbsLocker = new object();
        protected static readonly object vbsLocker2 = new object();

        protected uint BUFFER_SIZE = 512; //command buffer size
        
        public frmServer()
        {
            InitializeComponent();

            input = new inputFlags(); //instantiate input flags                       
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            if (btnStartServer.Enabled) //if this button is enabled
            {
                btnStartServer.Enabled = false; //disable this button

                input.bServerRunning = true; //note the server is now running

                Thread consoleThread = new Thread(unityComs2); //create a thread for unity coms
                consoleThread.IsBackground = true; //this thread runs in the background
                consoleThread.Start(); //start console coms

                Thread vbsThread = new Thread(vbsComs); //create a thread for vbs coms
                vbsThread.IsBackground = true; //this thread runs in the background
                vbsThread.Start(); //start vbs coms

                Thread vbsInputThread = new Thread(vbsInputComs); //create a thread for vbs input commands
                vbsInputThread.IsBackground = true; //this thread runs in the background
                vbsInputThread.Start(); //start vbs input coms

                Process clientLaunch = new Process(); //create process

                if (File.Exists("UBS_launchClients.bat")) //check if our client launch .bat exists
                {
                    clientLaunch.StartInfo.FileName="UBS_launchClients.bat"; //set the filename
                    clientLaunch.Start(); //execute bat
                    clientLaunch.WaitForExit(); //wait for it to finish
                }
            }
        }      

        private void consoleComs()
        {
            lock (consoleLocker) //engage console locker
            {
                if (input.bServerRunning)
                {
                    try
                    {
                        IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //set ip
                        TcpListener myList = new TcpListener(ipAd, 8001); //instantiate listener for console client with specified ip and port
                        
                        myList.Start(); //start console listener

                        do
                        {
                            AddItem("\nThe server is running at port 8001...");
                            AddItem("The local End point is  :" + myList.LocalEndpoint);
                            AddItem("Waiting for a connection.....");

                            Socket s = myList.AcceptSocket(); //answer incoming connection

                            byte[] b = new byte[BUFFER_SIZE]; //create a byte array to hold incoming data
                            int k = s.Receive(b); //save data in byte array (Receive() returns an int which is the length)
                            AddItem("Received...");
                            for (int i = 0; i < k; i++)
                            {
                                input.strCommandReceived += Convert.ToChar(b[i]).ToString(); //place command into our received command string
                            }
                            AddItem(input.strCommandReceived); //display received data

                            ASCIIEncoding asen = new ASCIIEncoding();

                            if (!input.bUnityClientUpdate) //if not a unity client update
                            {
                                s.Send(asen.GetBytes("The string was recieved by the server. HullRot: ")); //send general ack
                                AddItem("Sent Acknowledgement");
                            }

                            if (input.strCommandReceived == "stop") //stop server on "stop" command
                            {
                                input.bServerRunning = false; //turn off server
                            }
                            else
                            {
                                AddItem(input.scenario.doCommand(input.strCommandReceived)); //display result of this command for our current scenario
                            }

                            input.strCommandReceived = ""; //clear command received                        

                            /* clean up */
                            s.Close();
                        } while (input.bServerRunning);
                    }
                    catch (Exception e)
                    {
                        AddItem(e.Message);
                        MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
                    }
                }
            }
        }

        private void unityComs2()
        {
            lock (unityLocker) //engage unity locker
            {
                if (input.bServerRunning)
                {
                    try
                    {
                        IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //set ip
                        TcpListener myList = new TcpListener(ipAd, 8001); //instantiate listener for console client with specified ip and port

                        myList.Start(); //start console listener

                        do
                        {
                            AddItem("\nThe server is running at port 8001...");
                            AddItem("The local End point is  :" + myList.LocalEndpoint);
                            AddItem("Waiting for a connection.....");

                            Socket s = myList.AcceptSocket(); //answer incoming connection

                            byte[] b = new byte[BUFFER_SIZE]; //create a byte array to hold incoming data
                            int k = s.Receive(b); //save data in byte array (Receive() returns an int which is the length)
                            AddItem("Received...");
                            
                            for (int i = 0; i < k; i++)
                            {
                                input.strCommandReceived += Convert.ToChar(b[i]).ToString(); //place command into our received command string
                            }                           
                            AddItem(input.strCommandReceived); //display received data

                            ASCIIEncoding asen = new ASCIIEncoding();

                            if (!input.bVBSclientUpdate) //if not a vbs client update
                            {
                                s.Send(asen.GetBytes("The string was recieved by the server. Hull Rot: " + input.hullRot.ToString())); //send general ack with hull rot
                                AddItem("Sent Acknowledgement");
                            }

                            if (input.strCommandReceived == "stop") //stop server on "stop" command
                            {
                                input.bServerRunning = false; //turn off server
                                // btnStartServer.Enabled = true; //enable start server button
                            }
                            else if (input.strCommandReceived.Length>0) //if we have a command that's not blank
                            {                                
                                //bandaide//
                                if (input.strCommandReceived[0] == 'S' && input.strCommandReceived[input.strCommandReceived.Length - 1] == '?')
                                {
                                    string strBandaide = ""; //temporary container
                                    
                                    for (int iBandaide = 0; iBandaide < input.strCommandReceived.Length; iBandaide++) //loop throught command received string
                                    {
                                        if (input.strCommandReceived[iBandaide] != 'w') //if the current char is not a 'w'
                                        {
                                            strBandaide += input.strCommandReceived[iBandaide]; //add this char to the bandaide string
                                        }
                                        else { iBandaide = 999999; } //early exit of for loop
                                    }

                                    input.strCommandReceived = strBandaide; //dump fixed input back into strCommandReceived
                                }
                                //
                                
                                AddItem(input.scenario.doCommand(input.strCommandReceived)); //display result of this command for our current scenario
                            }

                            input.strCommandReceived = ""; //clear command received                        

                            /* clean up */
                            s.Close();
                        } while (input.bServerRunning);
                    }
                    catch (Exception e)
                    {
                        AddItem(e.Message);
                        MessageBox.Show(e.Message + "\n\nstrCommandReceived: " + input.strCommandReceived + "\n\n" + e.StackTrace);
                    }
                }
            }
        }

        private void vbsInputComs()
        {
            lock (vbsLocker2) //engage console locker2
            {
                if (input.bServerRunning)
                {
                    try
                    {
                        IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //set ip
                        TcpListener myList = new TcpListener(ipAd, 8003); //instantiate listener for console client with specified ip and port
                        
                        myList.Start(); //start console listener

                        do
                        {
                            AddItem("\nThe server is running at port 8003...");
                            AddItem("The local End point is  :" + myList.LocalEndpoint);
                            AddItem("Waiting for a connection.....");

                            Socket s = myList.AcceptSocket(); //answer incoming connection

                            byte[] b = new byte[BUFFER_SIZE]; //create a byte array to hold incoming data
                            int k = s.Receive(b); //save data in byte array (Receive() returns an int which is the length)
                            AddItem("Received...");

                            for (int i = 0; i < k; i++)
                            {
                                input.strVBSinputReceived += Convert.ToChar(b[i]).ToString(); //place command into our received command string
                            }
                            AddItem(input.strVBSinputReceived); //display received data

                            ASCIIEncoding asen = new ASCIIEncoding();

                            if (!input.bVBSclientUpdate) //if not a vbs client update
                            {
                                s.Send(asen.GetBytes("The string was recieved by the server.~")); //send general ack 
                                AddItem("Sent Acknowledgement");
                            }

                            if (input.strVBSinputReceived == "stop") //stop server on "stop" command
                            {
                                input.bServerRunning = false; //turn off server
                                // btnStartServer.Enabled = true; //enable start server button
                            }
                            else if (input.strVBSinputReceived.Length > 0) //if we have a command that's not blank
                            {
                                AddItem(input.scenario.doCommand(input.strVBSinputReceived)); //display result of this command for our current scenario
                            }

                            input.strVBSinputReceived = ""; //clear command received                        

                            /* clean up */
                            s.Close();
                        } while (input.bServerRunning);
                    }
                    catch (Exception e)
                    {
                        AddItem(e.Message);
                        MessageBox.Show(e.Message + "\n\nstrCommandReceived: " + input.strCommandReceived + "\n\n" + e.StackTrace);
                    }
                }
            }
        }       

        private void vbsComs()
        {
            lock (vbsLocker) //engage vbs locker
            {
                if (input.bServerRunning) //if the server is running
                {
                    try
                    {
                        IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //set ip

                        TcpListener myList = new TcpListener(ipAd, 8002); //instantiate listener with specified ip and port

                        myList.Start(); //start listening

                        do
                        {
                            AddItem("The server is running at port 8002...");
                            AddItem("The local End point is  :" + myList.LocalEndpoint);
                            AddItem("Waiting for a connection.....");

                            Socket s = myList.AcceptSocket(); //answer incoming connection
                            AddItem("Connection accepted from " + s.RemoteEndPoint);

                            byte[] b = new byte[BUFFER_SIZE]; //create a byte array to hold incoming data
                            int k = s.Receive(b); //save data in byte array (Receive() returns an int which is the length)
                            AddItem("Recieved...");
                            for (int i = 0; i < k; i++)
                            {
                                input.strVBScommandReceived += Convert.ToChar(b[i]).ToString(); //place command into our received command string
                            }
                            AddItem(input.strVBScommandReceived);

                            ASCIIEncoding asen = new ASCIIEncoding();
                            
                            if (input.strVBScommandReceived == "stop") //stop server on "stop" command
                            {
                                input.bServerRunning = false; //turn off server
                                btnStartServer.Enabled = true; //enable start server button
                            }
                            //if it's the vbs client
                            else if (input.strVBScommandReceived == "what about now?" || 
                                    (input.strVBScommandReceived[0]=='w' && input.strVBScommandReceived[14]=='?'))
                            {
                                if (input.bVBSclientUpdate) //if there's an update for vbs and enough time has elapsed
                                {
                                    s.Send(asen.GetBytes(input.strVBSclientUpdate)); //send instruction
                                    input.strVBSclientUpdate = ""; //clear vbs client update info
                                    input.bVBSclientUpdate = false; //we no longer have an instruction for vbs client                                    
                                }
                                else if (!input.bStab) //if stab is off
                                {
                                    //there used to be code here but was no longern needed, I kept the condition in so that the below else
                                    //is only called if this and the above conditions are not met
                                }
                                else { s.Send(asen.GetBytes("neg")); } //tell unity vbs to bugger off
                            }
                            else
                            {
                                string temp = input.scenario.doCommand(input.strVBScommandReceived); //grab the return string to get around cross thread bullshit
                                AddItem(temp); //display result of this command for our current scenario
                            }

                            input.strVBScommandReceived = ""; //clear command received

                            /* clean up */
                            s.Close();
                        } while (input.bServerRunning); //loop while the server is running

                        myList.Stop(); //stop listener
                    }
                    catch (Exception e)
                    {
                        AddItem("Error..... " + e.StackTrace);
                        MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
                    }
                }
            }
        }

        //GET AROUND CROSS-THREAD MOANING////////////////////////////////////////////////////////////////
        private delegate void stringDelegate(string _text);
        private void AddItem(string _text)
        {
            if (lbLog.InvokeRequired)
            {
                stringDelegate sd = new stringDelegate(AddItem);
                this.Invoke(sd, new object[] { _text });
            }
            else
            {
                lbLog.Items.Add((object)_text);
            }
        }       
        //////////////////////////////////////////////////////////////////////////////////////////////////

        private void tButtonLogic_Tick(object sender, EventArgs e) //ticks every 10ms
        {
            if (!input.bServerRunning && !btnStartServer.Enabled) { btnStartServer.Enabled = true; } //enable start server button if it's not when it should be

            if (lbLog.Items.Count > 0) { lbLog.SetSelected(lbLog.Items.Count - 1, true); } //keep the list box scrolled all the way down

            if (lbLog.Items.Count > 30) { lbLog.Items.RemoveAt(0); } //keep list no larger than 20 items
        }

        private void frmServer_FormClosed(object sender, FormClosedEventArgs e)
        {
            Process clientClose = new Process(); //create process to close clients

            if (File.Exists("UBS_closeClients.bat")) //check if our client close .bat exists
            {
                clientClose.StartInfo.FileName = "UBS_closeClients.bat"; //set the filename
                clientClose.Start(); //execute bat
                clientClose.WaitForExit(); //wait for it to finish
            }
        }
    }
}
UnityToUsToVBS.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace testServer5_ConsoleToUsToUnity
{
    public class UnityToUsToVBS : inputScenario
    {
        protected inputFlags input; //handle to input flags
        protected string tag; //our identifier for server output
        protected string returnString; //information we return

        public UnityToUsToVBS(inputFlags _input) //constructor
        {
            input = _input; //set handle to input flags
            tag = "UnityToUsToVBS"; //set our tag
        }

        public override string doCommand(string _command)
        {
            try
            {
                if (_command.Length > 0) //if this isn't an empty string
                {
                    //vbs commands
                    if (_command[0] == 'V' && _command[1] == 'B' && _command[2] == 'S')
                    {
                        //"VBS fire xxxx"
                        if (_command[4] == 'f' && _command[5] == 'i' && _command[6] == 'r' && _command[7] == 'e')
                        {
                            //"VBS fire main"
                            if (_command[9] == 'm' && _command[10] == 'a' && _command[11] == 'i' && _command[12] == 'n')
                            {
                                returnString = "VBS tank has fired main."; //set return string
                                input.bVBSclientUpdate = true; //note there is a command waiting for vbs
                                //set vbs script command
                                input.strVBSclientUpdate = "(vehicle player) selectWeapon \"caf_m256_cas_cannon\"; " +
                                                           "(vehicle player) setWeaponState [false, \"caf_m256_cas_cannon\",0]; " +
                                                           "(vehicle player) fire \"caf_m256_cas_cannon\";~";
                            }
                            //"VBS fire coax"
                            else if (_command[9] == 'c' && _command[10] == 'o' && _command[11] == 'a' && _command[12] == 'x')
                            {
                                returnString = "VBS tank has fired coax."; //set return string
                                input.bVBSclientUpdate = true; //note there is a command waiting for vbs
                                //set vbs script command
                                input.strVBSclientUpdate = "(vehicle player) selectWeapon \"caf_c6_veh_coax\"; " +
                                                           "(vehicle player) setWeaponState [false, \"caf_c6_veh_coax\",0]; " +
                                                           "(vehicle player) fire \"caf_c6_veh_coax\";~";
                            }
                        }
                    }
                    
                    //server commands
                    //"SERVER set turret rot #"
                    if (_command[0] == 'S' && _command[1] == 'E' && _command[2] == 'R' && _command[3] == 'V' && _command[4] == 'E' && _command[5] == 'R')
                    {
                        //set commands
                        //"SERVER set ..."
                        if (_command[7] == 's' && _command[8] == 'e' && _command[9] == 't')
                        {
                            //turret commands
                            //"SERVER set turret ..."
                            if (_command[11] == 't' && _command[12] == 'u' && _command[13] == 'r' && _command[14] == 'r' && _command[15] == 'e' &&
                                _command[16] == 't')
                            {
                                //set rotation/elevation
                                //"SERVER set turret rot ..."
                                if (_command[18] == 'r' && _command[19] == 'o' && _command[20] == 't') 
                                {
                                    string newRot = ""; //string to hold new rotation
                                    string newElev = ""; //string to hold new elevation
                                    bool bGrabbingElev = false; //are we grabing the elevation portion?
                                    for (int iRot = 22; iRot < _command.Length; iRot++) //loop through argument portion if the command string
                                    {
                                        if (!bGrabbingElev) //if we're not grabbing the elevation portion
                                        {
                                            if (_command[iRot] != ',') //if the current character is not a comma
                                            {
                                                newRot += _command[iRot]; //grab numeric portion of command string for rotation
                                            }
                                            else
                                            {
                                                bGrabbingElev = true; //start grabbing the elevation argument
                                                iRot++; //skip the space beside the comma
                                            }
                                        }
                                        else //we're grabing the elevation argument
                                        {
                                            newElev += _command[iRot]; //grab elevation argument
                                        }
                                    } 
                                    input.turretRot = (float)Convert.ToDecimal(newRot); //update server's turret rotation value                                   
                                    input.turretElev=(float)Convert.ToDecimal(newElev); //update server's turret elevation value

                                    returnString = "Server turret rotation value updated and sent to VBS.";
                                    input.bVBSclientUpdate = true; //note we have an update for vbs
                                    //input.turretRot *= -1.0f; //either vbs or unity is backwards, this sets things right
                                    input.turretElev *= -1.0f; //..
                                    if (!input.bStab) //if stab is off
                                    {
                                        //set vbs sctipt command to be sent to vbs
                                        /*input.strVBSclientUpdate = "(vehicle player) SetWeaponDirection [[0], [getDir (vehicle player)+" + input.turretRot.ToString() + ", " +
                                                                    input.turretElev.ToString() + "], true]~";*/

                                        input.strVBSclientUpdate = "(vehicle player) SetWeaponDirection [[0], [" + input.turretRot.ToString() + ", " +
                                                                    input.turretElev.ToString() + "], true]~";
                                    }
                                    else
                                    {
                                        //set vbs sctipt command to be sent to vbs
                                        input.strVBSclientUpdate = "(vehicle player) SetWeaponDirection [[0], [" + input.turretRot.ToString() + ", " +
                                                                    input.turretElev.ToString() + "], true]~";
                                    }
                                }
                            }
                            //stab commands
                            //"SERVER set stab ..."
                            else if (_command[11] == 's' && _command[12] == 't' && _command[13] == 'a' && _command[14] == 'b')
                            {
                                //"SERVER set stab on"
                                if (_command[16] == 'o' && _command[17] == 'n')
                                {
                                    returnString = "Server Stab set to on.";
                                    input.bStab = true;                                    
                                }
                                //"SERVER set stab off"
                                else if (_command[16] == 'o' && _command[17] == 'f' && _command[18] == 'f')
                                {
                                    returnString = "Server Stab set to off.";
                                    input.bStab = false;
                                    
                                    //input.stabOffTurretRot = input.turretRot; //set stab off turret rot
                                }
                            }
                            //hull rotation
                            //"SERVER set hullRot ..."
                            else if (_command[11] == 'h' && _command[12] == 'u' && _command[13] == 'l' && _command[14] == 'l' && _command[15] == 'R')
                            {
                                string newHullRot = ""; //holds new hull rotation as string
                                for (int iCommand = 19; iCommand < _command.Length; iCommand++)
                                {
                                    if (_command[iCommand] != ' ') { newHullRot += _command[iCommand]; } //grab next digit if we're not at a space
                                    else { iCommand = 99999; } //otherwise early exit of for loop
                                }
                                input.hullRot = (float)Convert.ToDecimal(newHullRot); //set new hull rotation

                                returnString = "Server hull rotation updated."; //set return string
                            }
                        }
                        //get commands
                        //"SERVER get ..."
                        if (_command[7] == 'g' && _command[8] == 'e' && _command[9] == 't')
                        {
                            //hull rot
                            //"SERVER get hullRot"
                            if (_command[11] == 'h' && _command[12] == 'u' && _command[13] == 'l' && _command[14] == 'l' && _command[15] == 'R')
                            {
                                returnString = "VBS hull rotation updated in unity client.";
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //AddItem(e.Message);
                //MessageBox.Show(e.Message + "\n\nstrCommandReceived: " + input.strCommandReceived + "\n\n" + e.StackTrace);
            }

            return returnString; //return result
        }
    }
}
 
^RETURN TO TOP^