Wednesday, December 15, 2010

Unity3D SmartFoxConnection and Connection Handler

Last time we left off, we put together our base extension and installed it into SmartFoxServer. This time we will be building our initial classes for Unity3D. So lets start by opening up the project we created earlier.

We'll start by making a few folders in the project view. We are going to create 4 base folders, Scenes, Common, Plugins, and Lobby. Under Common and Lobby we will create a folder called Scripts.

Now that our initial folder structure is created lets go ahead and save our scene to the scenes directory. I just call it Lobby to keep it simple.

Before we start working with SmartFoxServer we need to include the Unity3D SmartFox2.dll. Open an explorer window to [SFSInstallDir]\Client\Unity. You will see a file called SmartFox2.dll. Drag this file into Unity and put it in the Plugins directory you created.

Next we will create our SmartFoxConnection. This will be a singleton that will hold our connection no matter what scene we are on. Go ahead and create a C Sharp Script under Common\Scripts and call it SmartFoxConnection. It will contain the following:

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 SmartFoxConnection : MonoBehaviour
{
    private bool debug = true;
    private static SmartFox smartFox;


    public static SmartFox GetInstance()
    {
        if(smartFox == null)
        {
           smartFox = new SmartFox(debug);
        }
        return smartFox;
    }
}

So this sets up our singleton. For more information on the singleton pattern, go here.


Now, here is where i have a personal pet peeve. I hate reading tutorials where people don't take the time to make objects. They create a class that isn't reusable. They figure that by providing people with a chunk of code that they will just naturally learn to use patterns. So instead of just giving you the code we are going to go through some initial design to make our lives easier in the future.

Next we want to create another C Sharp Script in Common\Scripts and we will call it ConnectionHandler. Open it up in your editor and replace everything with the following:


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Sfs2X.Core;
using Sfs2X.Entities.Data;
using UnityEngine;
using Sfs2X;


public class ConnectionHandler : MonoBehaviour
{
}
We are starting with it empty so that I can discuss each piece as we run across it. To start, you will see a ton of references. These will be explained as we use them.

Between the braces go ahead and add :

    protected SmartFox smartFox;
    public bool debug = true;
This gives us a reference to SmartFox which is how we send our messages. Next we need to code our standard messages and functions for those messages - add the following below the 2 variables we added:
    protected void Awake()
    {
        Application.runInBackground = true;
        smartFox = SmartFoxConnection.GetInstance();
    }
This code tells the application that this script will be running the background. This means that even when you have your application minimized that this script will run. This is necessary so that we don't get a backlog of messages while our application doesn't have focus. Secondly we check to see if SmartFox is initialized and if so it gets the SmartFox connection. If it doesn't, it creates a new instance of it and puts it into debug mode. Realistically it will always get a connection.

Next we add our update function. Normally if you are used to using unity3d we use Update(). In this case we are going to use FixedUpdate(). The difference is that no matter what our frame rate it will always call FixedUpdate() at a fixed interval so it isn't dependent on graphics rendering. Again this is a necessity when dealing with messages.
    protected void FixedUpdate()
    {
        smartFox.ProcessEvents();
    }

Next we will create a function that will be used when switching scenes or when logging off or being disconnected.

    protected void UnregisterSFSSceneCallbacks()
    {
        // This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene
        smartFox.RemoveAllEventListeners();
    }

Next we want to create a function that will be called any time we are quitting. A forum post comments that unless you disconnect the client on the application close it will error out if you instantly try running again.
    protected void OnApplicationQuit()
    {
        if (smartFox.IsConnected)
        {
            UnregisterSFSSceneCallbacks();
            smartFox.Disconnect();
        }
    }

With me so far? Good. For now we are done with ConnectionHandler. It doesn't look like much, just your typical setup. But the nice thing is that now we don't every have to write this code ever again. This post is getting long so I'll put a break in here. Next post I'll cover our LobbyGUI which will present our user with an initial login screen we will be using.

3 comments:

Anonymous said...

The code returns the error:


Assets/Common/Scripts/ConnectionHandler.cs(21,39): error CS0120: An object reference is required to access non-static member `SmartFoxConnection.GetInstance()'

Unknown said...

Yes, I made a modification and didn't update appropriately. I updated it above. function should read:
public static SmartFox GetInstance()

Anonymous said...

thank u for these tutorials. Helped me a lot.

in the SmartFoxConnection script,
private bool debug = true;
wont work with
smartFox = new SmartFox(debug);

By adding a static it should work.
heres what it should be:

private static bool debug = true;

Thanks