0

Welcome to Lakehome Games

Lakehome Games is a tiny, but growing, game development studio working on our first commercial release.  We’re slowly becoming more active and recognized in the indie game development community.  We’re working hared to bring you our first commercial release – Chicken Spies!  Chicken Spies is an arcade-style adventure game with casual, fun puzzles — collect the corn, but don’t get caught!  Chicken Spies will be released on the iOS, PC, and  Web.

If you’d like the learn more about Lakehome Games, drop us a line:

darrelcusey@lakehomegames.com

0

City of Adventures GUI

Making a ton of progress this weekend on upgrading the City of Adventures GUI system (was using Unity GUI before, using NGUI now).  Login, signup, account activation, password recovery, and all error-handling for each of these is all working as-expected.  I <3 NGUI.

I’m planning on adding rotating screenshots of villain groups in the big open area in the login screen :)

coa_login

coa_registration

0

#GameOfLies

So… #GameOfLies has happened, and I’m completely hooked — well done @LunarPeter !

This seems like an appropriate match seeing as how we each received a 100,000 Zimbabwe Dollar note (expired):

“Game of Lies” is a film depicting the story of two men, Kurt Lyton a businessman and Erik Nelson an ex-convict. Neither of them know each other and have never met before, they have been randomly chosen by an extremely wealthy man whose identity is unknown. This man gives them both one hundred million pounds to do what they like with it but there is a catch, in exactly one month all the money will be collected back off them. It becomes a game of wits between them and only one can survive.

https://www.youtube.com/watch?v=BNBjEg-z4I0

So, my number is 90045901.  I have no idea if I’m supposed to share that number of not, but the first clue does say “find the others and work together and maybe I’ll let you be.”  So, from this, I am assuming this is a game where you win through collaboration and community-building??? Maybe???

Found So Far:

Here are the numbers that have been found so far.  Each appears to be a date in YYYYMMDD format. @LunarPeter tweeted that these were dates of wrongful executions.

19150929: Thomas Griffin and Meeks Griffin wrongfully executed.
19920211: Johhny Garrettt wrongfully executed.
20040217: Cameron Todd Willingham wrongfully executed.
90045901 (mixed up from 19900504): Jesse Tafero wrongfully executed
18631113: Chipita Rodriguez wrongfully executed
19891207: Carlos de Luna  wrongfully executed

Is there anything special about 19900504 because it was mixed up and the others were not?

…but then we have some “odd men out” – dates that don’t _seem_ to match-up to any wrongful executions (but maybe I’m missing something).  Both dates did have historic events, though:

20060801:  Death of Iris Marion Young, American political scientist and activist (b. 1949)

20070731:  “Operation Banner, the presence of the British Army in Northern Ireland, and longest-running British Army operation ever, comes to an end.”  Also: “The United Kingdom and the state of California made a deal to reduce their impacts on the environment together. Prime Minister Tony Blair and Governor Arnold Schwarzenegger reached the agreement after a visit by Blair to Long Beach. “

Does this mean people who have “20060801″ and “20070731″ are still in the game and the rest of us are dead???

Left out:

Conspicuously, the following well-know wrongful executions were left out (or perhaps just haven’t been found yet)…

1995????: Larry Griffin wrongfully executed
1993????: Ruben Cantu wrongfully executed
1997????: David Spence wrongfully executed
1997????: Joseph O’Dell  wrongfully executed
1998????: Leo Jones  wrongfully executed
1949????: Timothy Evans  wrongfully executed

@ME

“Don’t get mixed up while trying to find @me”.  So, this could be either @me or @em.

@em (Emma Watson twitter account is “EmWatson”) (Emily Worton twitter account is “em”)

@me (17.3K followers, doesn’t follow anyone).

 

0

City of Adventures

Here’s a few screenshots from what I’ve finally decided to call “City of Adventures” (this was “Project 1″ for those of you who have been following my Twitter stream :)

(sorry about the lame costumes in these early screenshots, they are just tests to make sure the costume shader is working)

dynamic_sky_cycleI have the sun & moon cycle working with a dynamic sky system.  The skies will slowly change palettes over several days (possibly weeks eventually).  Sunrises and sunsets could be bright and warm, or dark and foreboding.  Nights can be clear and quiet or stormy and cold.  The area lighting adjusts to the sky and cloud palettes so that it all feels very natural.

camera_controls_animations_2

Movements, animations and jumping are working now as well.  Now how do I get down from here?

camera_controls_animations

0

Updates!

After years of giving my projects “cute” names, I’ve decided to switch over to using numbers for project tiles: so, “project 1,” project 2,” and so on.  This works well for me because my brains works in discrete units like that – especially when it comes to programming.  I frequently find myself looking at a particular approach or solution and thinking “no, I want to approach 2 projects back” or “5 projects after this one.”  Using descriptive or “cute” labels (for me) makes it really hard to jump back and forth because I have to figure out the order from the arbitrary names.  Labeling all my project numerically makes it a breeze though.  Since I’ve just switched over to this system, though, I’m starting at Project 1.

There’s actually a Project 2 right now, too.  But, I can’t talk about it because it’s not mine — I’m just doing the programming for it, but believe me when I tell you … IT IS AMAZING!!!!

OK, so back to Project 1.  If you follow my Twitter feed, then you probably have guessed what I’m up to by now.  I’m currently working on the vertical slice and am making good, steady project.  It’s a huge project — especially for 1 person.  But, thankfully, people have started to volunteer to help me out — which is the most incredible thing ever.  I can’t wait to tell you all about it, but I want to make sure I can deliver everything I’m planning.  I want to under-promise and over-deliver, because… well, because society so often does the opposite to all of us.

So, for now, just some screenshots — pretty simple stuff, but it’s just me getting used to using procedural textures :)

alegorithmic_textures building_2 dynamic_sky_shader first_building late_19thc_road night_street_tunnel

 

 

…and here are some GUI screeshots.  If you don’t know what I’m up to after looking at these, then what were you doing in 2004????

class_builder1 class_builder2 costume_creator1 costume_creator2 costume_creator3

0

A Simple Observer Pattern for Unity 4.2

The Unity Package for this article can be downloaded here.

If you have been developing in Unity for awhile, you probably have found yourself writing code like this:

GameObject.Find("BigBoss").GetComponent<BossManager>.AddHealth(-20F);

Although code like this is fully functional, I am going to propose that you shouldn’t be doing it.  Here are some reasons why:

  1. If BigBoss loses its BossManager script in exchange for a generic EnemyManager script, all the scripts that try to reference the BossManager will break (even if EnemyManager does have an AddHealth() function).
  2. Whenever a new script is created that must also be notified of any health changes to BigBoss, you must modify every script that performs those changes (so that it also notifies the new script).
  3. If the AddHealth() function is changed to a UpdateStats() function, this will also break all scripts that reference this funtion.

In other words, what this does is create strong coupling between your classes.  When you do this, each class must have intimate knowledge of the class it is trying to access.  As your project grows, this will leads to hours of wasted time, unnecessarily complex code, and an inflexible framework.

One possible solution to this is to implement an Observer Pattern for your project.  Normally, these kinds of systems can be done with Events, Delegates, and Generics.  However, I would guess that most Indie game developers would struggle with the more esoteric formulations of this design pattern.  And while learning new things is great, sometimes you just want to finish your game.  This article will demonstrate an extremely simplified version of the Observer Pattern that will allow your classes to:

  1. publish and subscribe to events easily;
  2. reduce their coupling with other classes;
  3. easily expand the number and types of messages they can publish/subscribe to.

If you haven’t done so already, grab the Unity Package for this article, and open up the MessageManager script so you can follow along.  Let’s start with a Process Flow diagram that shows what’s going on (time moves from top to bottom):

simple_observer_2

At any point in the program, classes can register their interest in certain events with the MessageManager.  At any other time, any other class can generate a new message and send that message (with all the event information about the event) and send that on to the MessageManager.  The MessageManger will then turn around and send that event to all classes that have registered interest in that event.

The MessageManager knows which classes and methods it should send events to by using a little LINQ code as seen in the SendToListeners() method:

public void SendToListeners(Message m){
 foreach (var f in listeners.FindAll(l => l.ListenFor == m.MessageName)){ 
   f.ForwardToObject.BroadcastMessage(f.ForwardToMethod,m,SendMessageOptions.DontRequireReceiver);
   }
 }

There is one caveat to this solution — namely, all classes that will participate in publishing and subscribing to messages must have a reference to the MessageManager object.  Having just one “hard-coded” reference, though, is much better than having hundreds :)

One way you can easily fulfill this requirement (and the method I chose) is to simply make all classes that will be sending and receiving events a child  of the MessageBehaviour class.  We do this by creating an empty object named “World” and attaching the MessageManger script to it.

public class MessageBehaviour : MonoBehaviour {
protected MessageManager Messenger;
 public void Start(){ 
   Messenger = GameObject.Find("World").GetComponent<MessageManager>();
   OnStart();
 }
 protected virtual void OnStart(){
 }
}

…then each of our classes that will participate in publishing and subscribing to messages only needs to inherit from the MessageBehaviour class and implement the OnStart() method:

public class BigBoss : MessageBehaviour {
  protected override void OnStart () {
    // put code here that you would normally put in Start()
  }
}

We’ll do something very similar with all Message classes as well — each one will Inherit from a base Message class.  This still keeps our inheritance hierarchy extremely simple:

simple_observer_1

I like using dedicated classes for messages because then I incorporate “convenience functions” right into the message itself.  I didn’t do this for this sample, but you can imagine a subscriber needing the message information in a particular format.  Let’s say you have an IP address that is represented internally in the class as a 32-bit UINT.  A subscriber may instead need this information as a string — if your message is a class, then you can simply make a GetIPAddresssString() method in the class which will guarantee that all subscribers re-format the data in exactly the same way.

As you can see though, we need a way for our MessageManager to be able to handle LOTS of different message classes — some may only have a name/value pair while others could contain dozens of attributes.

To allow any number of different Message classes to be used with this system, we use inheritance again (composition works fine, though, as well).  We use a base Message class, and all other message inherit from it.  Because we are lazy programmers, and don’t like re-writing getters and setters for every child class of message, we’ll call the base constructor right in the signature like this.  We can see this in the definition of the NewPlayerMessage:

public class NewPlayerMessage : Message {
 public int PlayerGUID {get; set;}
 public NewPlayerMessage(GameObject s,string n,string v, int p) : base(s,n,v)
 {
   PlayerGUID = p;
 }
}

Now we can send either a generic Message, or the fancier NewPlayerMessage to the MessageManager’s SendToListeners() method.

Some things you may want to add to this system would include (again, I left these out to keep things as simple as possible):

  • An unsubscribe function to allow classes to stop receiving messages that no longer interest them
  • An automatic Message GUID system that would allow all message to have a globablly-unique ID that would be required for…
  • An acknowledgement system to allow classes to acknowledge to the sender that they did in-fact receive a given message

I hope you are able to use this implementation of the Observer pattern in your next Unity project.  As always, thanks for reading.

 

 

 

 

 

 

0

Character Customization in Unity Free

Currently working on a general-purpose set of shaders that can be used for any game where you need character customization in Unity.  Here are the requirements I set out for myself:

  • No hierarchical meshes – one seamless mesh (bone attachments are fine, though for things like armor, hats, hair, etc…)
  • Clothing “cut” (t-shirt or v-neck for example) must be able to be chosen independently for arms, legs, torso, and head
  • Any clothing diffuse texture (rivets and stitching in jeans for example) must be able to show up as if they appear “under” any patterns applied to clothing
  • Clothing should be able to have patterns applied to the top of it (a blend or a fire pattern for example)
  • Patterns should be able to be defined as a single texture, but mixed with player-chosen colors (at least 2).  For example, all patterns may be black and white, but the shader should be able to change the black parts to “color 1″ and the white parts to “color 2″ and then apply these on top of the clothing diffuse.  Patterns should be able to have any arbitrary scaling and offset as well.
  • Where the clothing cut defines there is no clothing (based on the alpha channel of the texture), a skin color (also player chosen) should show through
  • Each of the head, arms, legs, and torso should also be able to have an emblem that will also have its own color and will appear “on top” of any pattens and clothing diffuse color that have already been defined.  Emblems should be able to be scaled and positioned on each body part without repeating.
  • Overall, should layer as follows: skin –> clothing cut –> pattern mix –> emblem
  • All of these layers should be able to work completely independently in terms of their colors, textures, patterns, and emblems.
  • Also, must support bump mapping and specular highlighting.
  • Must work in Unity Free.

Most long-time MMO players will recognize this set of functionality as the “bare minimum” needed to support character customization.

So far, I have all of the above working.  Below are a couple screenshots of a single mesh character that meets all these requirements using the custom shader I wrote for Unity.

decals_mixer_bumpfirst_hair

 

Here’s the screenshot of the Unity properties panel for this shader where I am specifying all the textures, colors, patterns, and emblems independently for each part of the model — while still using a single seamless mesh:

custom_multi_bump_shader

 

Next up will be vertex morphing, a lot more attachments, and then a short video showing dozens of random combinations — should have thousands of possible combinations by that point :)

 

0

Server Migration in Unity 4.0.1

server_migration

Sometimes in game development, it really is best to simply “build your own,” iterating out from core functionality to final product.  This is especially true when you are trying to accommodate a game mechanic that is not served well by existing code bases.  Other times, a game engine or a piece of middleware will do everything you need it to do, and your only job is to simply integrate it correctly.  Unity Networking can be both these things – depending on what you are trying to accomplish.  I have heard the complaints about Unity’s networking model (and probably lodged quite a few myself); but I would also like to show that with a little extra work, you can extend the usefulness of Unity’s built-in networking to a much wider range of projects.

As you probably know by now, I have been writing a series of articles that demonstrate how Unity’s built-in networking can be used for peer-to-peer networking.  In my first article, I demonstrated how a single NetworkView could be used for each client (instead of 1 NetworkView per client and per player).  In my second article, I demonstrated how Server Discovery could be added to this as well.  Building on this foundation, this third article will demonstrate how Server Migration can be achieved.

For those of you unfamiliar with Server Migration… the simplest explanation is that it simply allows your multiplayer game to keep running even when the server has left the game.  One way to accomplish this (and the route we took) is by seamlessly changing the role of a chosen client to the role of server, having all other clients re-connect, and then the game continues.

Server Migration Goals

Server Migration must accomplish two goals:

  1. It must use a server-choosing scheme that will result in the same server being chosen by all clients simultaneously.  That way each client knows whether it will continue to be a client or if its role has changed to the server.
  2. It must guarantee that all clients have (or have access to) the same data that the server is using at any time to maintain game state should the server fail.

If you haven’t grabbed the Unity package yet for this article yet, go grab it from here, open up the NetworkController and let’s walk through some of the more interesting points.

Let’s also use this process flow diagram to make things a little easier to follow:

server_migration_overview

 

Let’s start with a brief overview of what’s happening here.  The Server Migration project is built on top of the Server Discovery project, so the Server Discovery pieces are not shown in the diagram above.  We’ll assume, though, that the client has found a server and successfully connected.  We’ll explain The Happy Path (left-hand side), and The Unhappy Path (right-hand side).

The Happy Path

Most of the time, the client (and server/client) is happily running through its Update() loop.  During that loop, though, we need to check to see if the game state has entered one of three special states: ServerStarting, ServerReconnecting or ServerAdding.

  • ServerStarting happens when the server has disconnected and the local client has determined that it will be the new server.
  • ServerReconnecting happens when the server has disconnected and the local client has determined that it will not be the new server (it will stay in the client role).
  • ServerAdding happens when the client has first connected to a server, and it is waiting a short amount of time before requesting the complete players list.

Each of these states includes a brief delay before they do their work and “back out” from that special state.  Technically speaking, it would be more robust to add an additional conversation between the client and server to let the server control when this transition happens.  I decided to leave those out, however, just to make it easier to see what’s going on — a simple time delay is sufficient for our needs.  Those cases follow this general pattern:

case((int)State.serverstarting):
 if(Time.realtimeSinceStartup > exitStateTime){
 statecontrol.PopState();
 StartServer();
 ListenForClients(statecontrol.GetLastGameName());
 }
 break;

As you can see from the diagram, before “backing out” of these special states, the client performs a different set of actions for each state.  The PopState() function is useful for sending us back to “wherever we were” in the game because the special states can be entered at any time — even during states the represent GUI menu states.  After all, if the server is going to fail, it doesn’t care if you are in the menu or not.

The Unhappy Path

Now that we’ve reviewed the management of these special states — let’s look at the right-hand side of the diagram which shows how those states are entered in the first place.  Before we do that, though, there are two subjects that we must cover…

Synchronicity Fail

From my testing, it appears as though the message dispatcher in Unity is completely independent of the Update() function loop.  In other words, they are asynchronous, or least neither relies upon execution of the other.  Don’t get me wrong, I’m not saying this is a Bad Thing.  However, we must take this into consideration because that means that it is extremely easy to get into a situation where we are generating an OnDisconnectedFromServer() over and over again — with no recourse for an Update() call to get out of it.  This can easily create an infinite loop.  Infinite loops are bad.

The same could be said for almost any built-in Unity message function — there is no guarantee that an Update() will get called in-between any two messages — or even get called at all.  Because of this, we need a way to “put a lock” on the messages so that we can deal with them and then prevent them from being called again until we specifically “unlock” them.  Those checks looks like this:

int cs = statecontrol.GetState();
 if((cs==(int)State.serverstarting) | (cs==(int)State.serverreconnecting)) return;

For this project, I only need this lock for the OnDisconnectedFromServer() message.  When this message is caught by this function, it guarantees that it will always push ServerStarting or ServerReconnecting onto the state stack.  I then check for either of these states at the top of the OnDisconnectedFromServer() function and make and early exit if that is the state we are in.  The Update() function will see these states, and after a short delay, will do the work required to exit those states and finally pop the states off the stack.

The Deal with The NetworkPlayer Struct

I really hope that someone is able to prove me wrong, about this — because it would sure be convenient to use the NetworkPlayer struct (“NPS” for short) to pass-around client data.  All my testing, however, can only lead me to one conclusion — Unity is hard-coded to prevent sending an NPS to a “third party.”  In other words, the client and the server for any given connection can freely pass that client or that server’s NPS back and forth — but one client’s NPS can’t be sent to another client.  Client A can never receive the NPS of client B.

If you think about it, this is a Good Thing because you probably don’t want to expose both your internal (NAT) and external (WAN) IP addresses and ports to a complete stranger (ie. another player in a game that you don’t even know).  I can see how maybe Unity did this on purpose — but it seems odd that they’d go out of their way to do so.  Perhaps RakNet did it for them though :)

In any case, it doesn’t really have that much effect on us — we’ll just send the information we need to send “manually.”  This amounts to little more than adding a couple of additional attributes to the JoinPlayer() signature and makes the code more self-documenting anyways :p

[RPC]
 void JoinPlayer(string ip, int p, string g, Vector3 pos, NetworkViewID nv){
...
}

Back to the Unhappy Path

OK… now that we’ve got those two discussion behind us, all we really need to cover is the function that is used on all clients to come to the same conclusion about who should be the next server.  It’s easy, actually — which just pick the client with the lowest GUID value.  Because all clients know the GUIDs of all other clients, they will all come to the same conclusion.  It also gives us a really good excuse for using LINQ — everyone wins:

chosenServer = players.Aggregate((c, d) => Convert.ToUInt64(c.guid) < Convert.ToUInt64(d.guid) ? c : d);

Returning to The Happy Path

So, there we have it.  When the server disconnects, each client will independently come to the same conclusion about who will be the next server.  The client that has the lowest GUID value will start up a new server and start listening for connections.  The other clients will wait a small delay and then connect to the new server.  The new server will automatically re-associate the connecting clients with their existing game objects at their current locations, and the game continues :)

I hope you enjoyed this article, as always thanks for reading!

 

2

Server Discovery in Unity 4.0.1

This Unity Package can be downloaded here (updated):

server_discovery_sample_2013_03_07.unitypackage

For most developers, Unity truly goes out of its way to make things as easy as possible for game development.  For example, switching your camera type from perspective to orthographic takes just a click of a button.  Switching lights from spot, to directional, to area; again, just a click of a button.  However, there are a few parts of Unity that, surprisingly, have no options whatsoever.  One of these parts is Unity’s networking design.  Unity is stubbornly Client-Server in its networking design.  There’s no drop-down box where you can switch it over to peer-to-peer networking – this is left as an exercise for the programmer.

A peer-to-peer system, though, can be developed on top of Unity’s existing client server networking framework by adding additional components that will allow the server to migrate among all networked clients.  Minimally, we’ll need to build 3 components: Shared State, Server Discovery and Server Migration.  In my previous article, I described a simple FPS Networking Sample that could maintain state across all clients using a single NetworkView on each client.  An additional advantage to this system is that each client maintained the same information as the “server.”  Because of this, the Shared State requirement has already been met.  The clients are not sharing a lot of information (just the list of players and their locations and targets)… but for now, that’s sufficient.

In this article, I’ll tackle Server Discovery and finally demonstrate Server Migration in a follow-up article.  I’m going to review the most important parts of this solution, so if you haven’t already grabbed the Unity package above, you should do so now so you can follow along.  Let’s start with a process flow diagram…

server_discovery_overview

One of my design goals for this solution was to make it so that a client could easily switch over to become a server at any time.  Until we put in the last Server Migration piece, this is done manually by following these steps:

  1. Start a single-player game
  2. Hit Escape
  3. Select “Open to LAN”

Now your game will be available to others, but most importantly you are able to start a single player game without connecting to a server first.  If you look at a lot of other Unity Networking tutorials, this isn’t even possible.  A lot of other tutorials will use Network.Instantiate(), or else make it so that the client only instantiates a player upon the specific direction of the server.  So, how do we both instantiate at the direction of the server while not actually being connected to a sever?

Easy.  We fake it.  In the diagram above (highlighted in blue), FakeServerJoin() is always executed in any single player game.  This function will start a local server (which won’t actually be used at this point) and then use that local Unity server instance to allocate its own network view.  This is okay to do because (if we become a server later) any clients that connect to us will be drawing network views from the same view ID pool — so there’s no duplication of view IDs.

Also, notice how we create a new NetworkPlayer instance, just by calling its default constructor.  Normally, your NetworkPlayer instance is something that is created and populated “behind the scenes” for OnPlayerConnected().  Because we’re not actually connecting to a server here, OnPlayerConnected() will never get called.  But that’s okay because NetworkPlayer’s default constructor will create “good enough” default values that won’t interfere with any real network players that may connect to us later.  We just allocate a newtwork view, create a default NetworkPlayer instance, send it all along to the JoinPlayer() function, and pretend these aren’t the droids we’re looking for… move along… move along.

At any point now, we can open the game to the LAN and people can connect to us normally.

So, now let’s see what happens when we open the game to the LAN — this is where the real Server Discovery functions come into play.  You may have noticed that Unity doesn’t have a “Network.Broadcast()” function — and why would it?  It strictly adheres to a client-server networking model, after all.  It assumes that the client MUST know the IP address of the server.  So, how do we communicate with a server when we don’t know its IP address (or even if there is a server out there to talk to)?

To accomplish that, the ListenServer() function (highlighted in red) has to do some lower-level networking work.  It has to create its own IPEndPoint, create a UdpClient, and create a UdpState.  These can all be done with just a single statement each — so, it’s not exactly re-inventing the wheel.

However, there are a couple things we need to be careful with.  First and foremost, we must use a random port every time this function is called.  In a given application session, you cannot create 2 UdPClients with the same IP address and same port.  Unity will complain about this and generate a runtime error.  You would see this error on the client if the client connected, dropped, and then tried to rejoin without restarting the application.  The client shouldn’t have to restart the application to re-join, so we have to solve for this limitation.

Update:  I found out that you could actually use 0 for the port number as long as you preset the minPort and maxPort.  This might be a slight improvement as (supposedly) the same port will not be chosen if port 0 is used repeatedly.  If you are feeling adventurous, you may want to try that.

To get around this, we randomize the port on which we’re going to listen for server broadcast responses.  Because the server doesn’t know what port we’re listening on, we have to tell it what that port number is — we do this by sending our listening port number on the server’s known port (which it previously opened for listening for client broadcasts).

Let’s summarize before going further:

  • Server open client listener on Known Port (15000)
  • Client opens a listener on a Random Port (15001 to 15999)
  • Client sends on Known Port to the server its chosen Random Port
  • Server responds to client on the client’s chosen Random Port

Also notice that we are using a lot of asynchronous callbacks.  This is done both in the ListenServer() function and in the ListenForClients() function (highlighted in yellow).  This will (effectively) create a separate thread on which we can react when the conditions for the callback are met.  This is great for a client because it allows the client to still play locally while hosting a game and while the listener thread is independently listening for client join requests :)

It also completely sidesteps the whole “Connect is Blocking” problem (which we’re not even going to talk about here — that would be a whole separate article).  The BeginReceive(new AsyncCallback(ListenServerCallback), us1) function will call the function “ListenServerCallback” when a response is received back on our client’s chosen  Randomly Port number and operate completely on a separate thread.  For the server, the same thing happens with the BeginReceive(new AsyncCallback(ListenForClientsCallback), us1) function, but this time it calls the ListenForClients function when a client sends a message on the Known Port.

Note as well that just opening a listening port won’t (of course) cause a server to respond — so, we have to actually send a message to the server.  This is done with the FindServer() function.  We could send a message to the server something like, “Looking for Server Discovery server,” but that would be a waste.  The server needs to know the chosen Random Port on which we’re listening for responses, so we’ll send that instead.  Notice too that we specifically have to turn on the capability for the UdpClient to broadcast with “uc2.EnableBroadcast = true;” — it’s off by default.

The last point I wanted to discuss here is the need for a Thread.Sleep() function call.  This is needed so that those separate threads that have been started can get a chance to get some processing time.  This must be done any time an asynchronous function is used, so it’s just easiest to put this in the networkController’s Update() function.  The integer it accepts is the number of milliseconds to block the current thread — thereby allowing the listeners some time to check their buffers and execute the callbacks if any messages have been received.

So, that’s pretty much all there is to it.  Adding Server Discovery to Unity.  We’re now two-thirds of the way done to having a full peer-to-peer Unity client.

If you liked this article, please follow me on Twitter @Tulrath to know first when the final part of this series is published.

As always, thanks for reading!

0

Reflection and Name/Value Pairs

Using Reflection in C# to create a class with a constructor that can set its properties from a delimited name/value pair string.  Just what it says:

public class Creature
{
   public int version { get; private set; }
   public int guid { get; private set; }
   public string name { get; private set; }
   public int health { get; private set; }
   public int status { get; private set; }
   public int skill1 { get; private set; }
   public int skill2 { get; private set; }
   public int skill3 { get; private set; }
   public int skill4 { get; private set; }
   public int ability { get; private set; }
   public int special { get; private set; }
   public int type { get; private set; }
      
   // create a creature using a record string
   public Creature(string str)
   {
      
      char[] delims = new char[]{ ‘|’, ‘,’ };
      char[] assigns = new char[]{ ‘=’ };
      string[] pairs = str.Split(delims);
      Type type = this.GetType();
        PropertyInfo[] properties = type.GetProperties();
 
      foreach(string pair in pairs)
      {
         string pairName = pair.Split(assigns)[0];
         string pairValue  = pair.Split(assigns)[1];
         
         foreach(PropertyInfo propertyInfo in properties)
         {
            if(propertyInfo.Name == pairName)
            {
               this.SetProperty(propertyInfo, pairValue);
            }
         }
         
      }
      
   }
   
   public void SetProperty(PropertyInfo propertyInfo, object value)
    {
        switch(propertyInfo.PropertyType.Name)
        {
            case “Int32″:
                propertyInfo.SetValue(this, Convert.ToInt32(value), null);
                break;
            case “String”:
                propertyInfo.SetValue(this, value.ToString(), null);
                break;
        }
    }
}

…creating an instance of the class with properties set to the values of a name/value pair string is this easy:

Creature c = new Creature(“version=1|guid=1|name=red spider|health=10|skill1=1|skill2=2|type=1″);