Talk:Multiplayer with Unity and SmartFox tutorial
From Unify Community Wiki
In order to using this tutorial with SmartFoxServer2x I modified the two .cs script.
GUI LOGIN
using UnityEngine; using System; using System.Collections; // for using hash tables using System.Security.Permissions; // for getting the socket policy using Sfs2X; // to setup SmartFox connection using Sfs2X.Core; // necessary to access the room resource using Sfs2X.Requests; public class gui_Login : MonoBehaviour { // sfs variables private SmartFox sfs; private string serverIP = "192.168.56.1"; private int serverPort = 9933; // default = 9339 public string zone = "city"; public bool debug = true; // variables used in script private string statusMessage = ""; private string username = ""; void Awake() { Application.runInBackground = true; // Let the application be running while the window is not active. // Create SmartFox connection if not already available if ( SmartFox1.IsInitialized() ) { Debug.Log("SmartFox is already initialized, reusing connection"); sfs = SmartFox1.Connection; } else { if( Application.platform == RuntimePlatform.WindowsWebPlayer ) { // Only set this for the webplayer, it breaks pc standalone // See http://answers.unity3d.com/questions/25122/ for details Security.PrefetchSocketPolicy(serverIP, serverPort); } try { Debug.Log("Starting new SmartFoxClient"); sfs = new SmartFox(debug); sfs.ThreadSafeMode = true; //sfs.runInQueueMode = true; } catch ( Exception e ) { Debug.Log(e.ToString()); } } // Register callback delegates, before callling Connect() sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection); sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost); sfs.AddEventListener(SFSEvent.LOGIN, OnLogin); //SFSEvent.onRoomListUpdate += OnRoomList; // da controllare sfs.AddEventListener(SFSEvent.DEBUG_MESSAGE, OnDebugMessage); //SFSEvent.onJoinRoom += OnJoinRoom; // We will not join a room in this level Debug.Log("Attempting to connect to SmartFoxServer"); sfs.Connect(serverIP, serverPort); } void Update() { sfs.ProcessEvents(); } void OnGUI() { // server IP in bottom left corner GUI.Label(new Rect(10, Screen.height-25, 200, 24), "Server: " + serverIP); // quit button in bottom right corner if ( Application.platform != RuntimePlatform.WindowsWebPlayer ) { if ( GUI.Button(new Rect(Screen.width-150, Screen.height - 50, 100, 24), "Quit") ) { sfs.Disconnect(); UnregisterSFSSceneCallbacks(); Application.Quit(); } } // Show login fields if connected and reconnect button if disconnect if (sfs.IsConnected) { GUI.Label(new Rect(10, 116, 100, 100), "Username: "); username = GUI.TextField(new Rect(100, 116, 200, 20), username, 25); if ( GUI.Button(new Rect(100, 166, 100, 24), "Login") || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) { sfs.Send(new LoginRequest(username, "", zone)); } } else { if ( GUI.Button(new Rect(100, 166, 100, 24), "Reconnect") || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) { Application.LoadLevel("sc_City"); } } // Draw box for status messages, if one is given // Contains some logic to parse message of multiple lines if necessary if (statusMessage.Length > 0) { int boxLength = 61; // define length of status box int messageLength = statusMessage.Length; // get length of status message string originalMessage = statusMessage; // copy message in to work string string formattedMessage = ""; // define output message string int i = 0; while (i + boxLength < messageLength) // iterate and add newline until over length { formattedMessage = formattedMessage + originalMessage.Substring(i,boxLength) + "\n"; i = i + boxLength; } // add last piece of original message formattedMessage = formattedMessage + originalMessage.Substring(i, boxLength - (i + boxLength - messageLength)); // draw status box with message GUI.Box (new Rect (Screen.width - 420,10,400,48), formattedMessage); } } private void UnregisterSFSSceneCallbacks() { // This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection); sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost); sfs.AddEventListener(SFSEvent.LOGIN, OnLogin); sfs.AddEventListener(SFSEvent.DEBUG_MESSAGE, OnDebugMessage); //SFSEvent.onJoinRoom -= OnJoinRoom; } void OnConnection(BaseEvent e) { if ( (bool)e.Params["success"] ) { SmartFox1.Connection = sfs; statusMessage = "Connected to SmartFox Server"; Debug.Log(statusMessage); } else { statusMessage = "Can't connect! " + (String)e.Params["error"]; Debug.Log(statusMessage); } } void OnConnectionLost(BaseEvent e) { statusMessage = "Connection lost / no connection to server"; } public void OnDebugMessage(BaseEvent e) { Debug.Log("[SFS DEBUG] " + (String)e.Params["message"]); } public void OnLogin(BaseEvent e) { if ( (bool)e.Params["success"] ) { statusMessage = "Login for user \"" + (String)e.Params["name"] + "\" successful."; // Lets wait for the room list } else { // Login failed - lets display the error message sent to us statusMessage = "Login error: " + (String)e.Params["error"]; } } /* // We will not join a room in this level, the NetworkController in the next scene will take care of that void OnJoinRoom(Room room) { Debug.Log("Room " + room.GetName() + " joined successfully"); sfs.SendPublicMessage(sfs.myUserName + " has joined"); // We can now move on to the next level UnregisterSFSSceneCallbacks(); Application.LoadLevel("sc_City"); } */ /* void OnRoomList(Hashtable roomList) { try { foreach (int roomId in roomList.Keys) { Room room = (Room)roomList[roomId]; if (room.IsPrivate()) { Debug.Log("Room id: " + roomId + " has name: " + room.GetName() + "(private)"); } Debug.Log("Room id: " + roomId + " has name: " + room.GetName()); } // Users always have to be in a room, but we'll do that in the next level /* if (sfs.GetActiveRoom() == null) { sfs.JoinRoom("Central Square"); }*/ /* UnregisterSFSSceneCallbacks(); Application.LoadLevel("sc_City"); } catch (Exception e) { Debug.Log("Room list error: "+e.Message+" "+e.StackTrace); } }*/ }
SMART FOX
using UnityEngine; using Sfs2X; // Statics for holding the connection to the SFS server end // Can then be queried from the entire game to get the connection public class SmartFox1 : MonoBehaviour { private static SmartFox smartFox; public static SmartFox Connection { get { return smartFox; } set { smartFox = value; } } public static bool IsInitialized() { if ( smartFox != null ) { return true; } return false; } }