Hassle Free Level Boundaries in Unity3D

Creating constrained areas and general level boundaries can become tedious when dealing with more complicated design and structure.  In the programming world, we call this giant waste of time boiler code.  I suppose in the level design world, we can call it boiler design.

You can spend an hour or so adding in custom colliders to shape the bounds of your areas or levels.  But, what happens if the scale was off and you need to tweak a few things… you have to go through and adjust everything (especially for height).  This is a lot of wasted time and effort where it could be applied to what will count: your game/simulation/product.

Fortunately, there is a new tool available on the asset store.  The Boundary Tool allows rapid creation of collision areas and each can be grouped and color coded for reference.  They also can overlay to your scene view and they do not get in the way when dragging prefabs/models into the scene to place it on an actual mesh or terrain.  It also supports tweaking the collision areas during editor playback so you can truly test the positioning of the “invisible walls” and your characters without the risk of publishing a level that has map exploits.

There is absolutely no integration code to be done.  It is an editor extension designed for artists and level designers or a programmer who doesn’t have time for tooling when they could focus on gameplay and mechanics.

Here are some videos of it in action:

Disclaimer: I worked on this tool.  However, it still addresses a large time sink in the level design workflow.

Unity3D NavMeshAgent for Player Control

I was searching through the sparse official documentation on NavMesh and NavMeshAgent and found very little functional explainations and implementation.  So I decided to just play with it… whats the worst that could happen, right?

Note: This requires Unity3D Pro – NavMesh baking is only supported in Pro.  Also, I have not played much with the A* extension Aron Granberg put together.  It looks great however for true A* and I intend to play with it.

Most examples and tutorials and posts out there all utilize NavMesh for controlling AI characters.  And they typically are all “make AI follow this sphere you can move around”.  Kudos to all those efforts, as they are still very useful.  However, I was looking for a different solution.  I wanted pathfinding very quickly for my character and not AI, backed with a Click To Move style controller.

Step 1. Unity3D Pro.  Check.

Step 2. Plane or smashed cube to “walk on”.  Throw in more simple geometry for walls and “steps”.  I quote walk on and steps because they are configurable to a great degree.  Layer masking for walkable surface types and like most character controllers, the steps have max height values (navmeshagents also have jump heights too which is neat).

Step 3. Window->Navigation.  Check the Show NavMesh button in the window that overlayers the scene (if you dont see this make sure the Navigation tab is selected near the Inspector window… showing that window defaults it to tab next to Inspector).

Step 4. On Navigation tab, click bake.  You’ll see all of the blue shading that shows the navmesh an agent can traverse.

So that is simple enough.  The scene now includes all the pathing information.  Now to let my player use the navmesh, I have to make it an agent.  I’d stress this point: while learning this, do not make the assumption that NavMeshAgent’s are AI.  They don’t have to be.  Is that its intended use? Maybe. Probably.  Doesn’t mean its only use is controlling AI.  I am not going to delve into click to move style 3rd person controlling.  I will assume you have a rig already, or just using basic geometry with a nested camera to track movement.

Step 5. Add NavMeshAgent component to whatever gameobject that you want to adjust the transform for.  This is an important note…  A basic approach in scene graphs is nesting objects to inherit transforms.  Whereever the agent is, becomes the “root” that moves.

Step 6. In the click to move method, you essentially cast a ray from mouseclick to intersect with geometry / terrain that is generally on specific layers.  Having that destination vector allows the agent to kick off.  NavMeshAgent::SetDestination(Vector3).  To the right is a very crude detection and implementation.

A feature I wanted was to stop the player on a current path either by choice (forcing an action in place) or not by choice(player gets rooted by an enemy).  So some more exploratory programming was needed.  Fortunately, NavMeshAgent::Stop exists.  It has an override to disable updates.  This is critical.  I was getting rotation snapping results when I was trying to orient a “rooted” player towards the current mouse click.  Without stopping the agent transform updates, when you set a new destination or resume the path, the controlled object will snap back to its “nav mesh” tranform and not begin where the lookAt vector3 rotation was last (because its not applied through the nav mesh component, but to the object itself).

Note: If anyone knows a way to bypass this completely and control it via the NavMeshAgent component – I’m all ears… I’d prefer that.  It was late however, and I didn’t want to spend more time on this before moving on.

Consuming a WCF Service from Unity3D

Unity3D is running MONO.Net and WCF implementation was for some time being worked on under “Moonlight 3.5” for MONO.  It has been merged into the main distribution of MONO for a while now; and yes, Unity3D supports it.  I will assume if you are reading this, you know how to create and host WCF services so I will not touch that at all.

Assumption: You have a WCF service running on your local IIS server at: http://localhost:8080/MyService.svc

There are a few infrastructural steps involved on the Unity3D side:

  • Setting API compatibility
  • Add plugins to project tree
  • Generate and add client proxy
  • Add gateway specific to the Unity3D application

Setting API compatibility

By default, Unity3D uses a stripped down version of the MONO framework.  You can consider this similar to .Net 4.0’s Client Profile versus Full version.  This setting can be changed through the menu bar: Edit -> Project Settings -> Player.  It needs to be set to 2.0 and not 2.0 Subset.

Add plugins to project tree

Unity3D’s runtime will enumerate a specific folder for assemblies and make those references available to the scripting engine “globally”.  At the root level, simply create “Plugins”.  Any assembly you package and use as a business layer should be deployed here.

In the new container folder, you need to add the MONO assembly compilations for the standard WCF assemblies you’d normally use in a Microsoft .Net Framework runtime.  Navigate to your Unity3D installation directory and start diving into the mono 2.0 location (for a point of reference, mine is: C:\Program Files (x86)\Unity\Editor\Data\Mono\lib\mono\2.0).

You will need to copy three assemblies into the Plugins container:

  • System.Runtime.Serialization
  • System.Security
  • System.ServiceModel

Generate and add client proxy

Add another container named “ClientProxies”.  This can technically be nested under “Scripts” or whatever folder convention / structure you may have or desire (Plugins is the only engine specific folder).  Now run the Visual Studio Command Prompt and navigate to the ClientProxies folder (this will have the generated proxy code placed here automatically, you can alternatively generate it anywhere on your filesystem and move/copy it into this container).  Generate the proxy class using SVCUTIL

svcutil -out:MyServiceClient.cs http://localhost:8080/MyService.svc?wsdl

This will generate the same files that get created when adding a Web Service reference through Visual Studio.

Add gateway specific to the Unity3D application

Now all that remains is writing a gateway script that will use the newly created client proxy as an object and execute methods off the service.  You do this the same as any ofther WCF in-code call.  You will access to the MyServiceClient object type now, and can pass in the endpoint and binding information through the constructor.

Thats all!

Unity3D – Access another object’s script values

This is useful to share information between game objects. Specifically, show the life of a player (tracked in script) on the HUD… you can set the UI element’s content to the value from the player’s script component that tracks the life value.

public class OtherScript MonoBehaviour
{
    public int VariableOne = 2;
    public int VariableTwo = 1;

    public int Result;

    void Start()
    {
        Result = VariableOne + VariableTwo;
    }
}
public class SomeOtherScript : MonoBehaviour
{
    void Start()
    {
        GameObject otherObject = GameObject.Find("OtherObjectThatHasScript");
        OtherScript otherObjectsScriptComponent = (OtherScript)otherObject.GetComponent(typeof(OtherScript));

        Debug.Log(string.Format("Result: {0}", otherObjectsScriptComponent.Result));
    }
}