Category Archives: Unity

Unity Lifetime Manager

If you’ve ever used an IoC container, you’ll know that one of their benefits and burdens is that they abstract away from you the hassle of managing your dependencies. Just declare your interfaces as constructor parameters and then register those dependencies at startup, and the IoC container will propogate your class. Your registration may look like this:

    container.RegisterType<IMyService, MyService>();

But what about when your class has state? For example, what if I have this sort of thing:

    container.RegisterType<IMyData, MyData>();

Here we’re using unity, but it appears that the default behaviour for most IoC containers is transient – that is, they are created each time they are resolved. This is important, not just because you will lose data that you thought you had (in fact that’s one of the better scenarios – because it’s obvious that it’s not behaving how you expect), but because if you’re caching results of queries and so forth, you might find your application is going back for data that you thought it already had. Here’s an example, using Unity, that proves this:

static void Main(string[] args)
{
    var container = new UnityContainer();
 
    container.RegisterType<IMyService, MyService>();
    container.RegisterType<IMyData, MyData>();
 
    container.Resolve<IMyData>().Test = "testing";
    container.Resolve<IMyService>().TestFunction();
 
    Console.ReadLine();
}

The service class might look like this:

public interface IMyService
{
    void TestFunction();
}
 
public class MyService : IMyService
{
    private readonly IMyData myData;
 
    public MyService(IMyData myData)
    {
        this.myData = myData;
    }
 
    public void TestFunction()
    {
        Console.WriteLine($"Test Data: {myData.Test}");
    }
}

And the data class:

public interface IMyData
{
    string Test { get; set; }
}
public class MyData : IMyData
{
    public string Test { get; set; }
}

If you run that, you’ll see that the output is:

Test Data: 

Different IoC containers have slightly different life times – in fact, in the .Net Core IoC, you have to now explicitly register as Singleton, Transient or Scoped. In Unity, you can do something like this:

static void Main(string[] args)
{
    var container = new UnityContainer();
 
    container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
    container.RegisterType<IMyData, MyData>(new ContainerControlledLifetimeManager());
 
    container.Resolve<IMyData>().Test = "testing";
    container.Resolve<IMyService>().TestFunction();
 
    Console.ReadLine();
}

Building Block Game in Unity 3D

Not sure this qualifies as a game, but it’s a computerised version of the building blocks that you might give to a three-year-old. What can I say, it was a nice way to spend a Sunday afternoon !

Here’s what the finished game / program looks like:

The Script

There is only one script:

public class BehaviourScript : MonoBehaviour
{
    
    private Vector3 screenPoint;
    private Vector3 offset;
 
    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }
 
    void OnMouseDrag()
    {
        Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
 
        if (cursorPosition.y > 0)
        {
            transform.position = cursorPosition;
        }
    }
}

The Scene

Basically, the blocks are standard unit cubes with a wood texture, a rigid body and the above script attached:

Mesh Colliders in Unity

Mesh colliders are, generally speaking, a bad idea in Unity. The reason being that they cause collision based on the detailed mesh that forms the object. This is bad, basically because this generates many collision points. Consider this object:

meshcollider1

As you can see, it’s a basic cylinder (a cup), so a box collider would add eight collision points. A mesh collider generates a point for each of the 496 vertices.

meshcollider2

So, whilst it’s more accurate, it uses more resources.

Okay, so now I’ve said why you shouldn’t use a mesh collider, I’ll cover how to use them.

Firstly, you need to add a mesh collider:

meshcollider3

There are three important things to note here:

  1. There is a mesh collider
  2. It is convex
    1. The convex flag allows the collider to collide with other colliders
  3. It is not a trigger
    1. The trigger flag turns the collision into a programmatic notification only

The manual for this is here.

Adding Cheats and Features to a Unity Game for Development Only

I’m currently writing a breakout style game (which, if you’ve seen any of my previous posts, you might have divined). One of the things that I would like to do with this, without having to play through all the levels is to complete the level quickly. This led me down the path of creating a “Cheat” button. However, for those amongst you that remember the ZX Spectrum, the makers of Jet Set Willy may have had a similar idea, but left the “Pokes” in the final game.

To avoid this, I thought it must be possible to use a feature such as the compiler directive in C#. In fact it is. Unity has its own, and one is to determine whether you’re running in the editor.

Here’s how I conditionally display the button:

    void OnGUI()
    {
#if UNITY_EDITOR
        if (GUI.Button(new Rect(10, 30, 50, 30), "Cheat"))
        {
            var o = GameObject.FindGameObjectsWithTag("Brick");
            foreach (var b in o)
            {
                var r = b.GetComponent<Rigidbody>();
	        r.transform.position += new Vector3(0, 0, zOffset);
                r.useGravity = true;
            }
        }
#endif
    }

This particular cheat just makes all of the bricks fall out of the sky. UNITY_EDITOR is one of a list of pre-defined “Platform Defines” that can be found here.

Saving and Loading Level Data in Unity

This describes a method of persisting data in Unity. For example, saving and loading the current game level.

The first thing that you will need is to create a helper class to read and write the data that you need:

        public static void SaveGameState()
        {
            XmlDocument xml = new XmlDocument();
            var el = xml.CreateElement("PlayerStatus");
            el.SetAttribute("CurrentLevel", Application.loadedLevel.ToString());
            xml.AppendChild(el);
            xml.Save("data.xml");
        }

        public static void LoadGameState()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load("data.xml");
            var el = xml.GetElementsByTagName("PlayerStatus")[0];
            string currentLevel = el.Attributes["CurrentLevel"].Value;
            int loadLevel = 0;
            if (!string.IsNullOrEmpty(currentLevel))
            {
                loadLevel = int.Parse(currentLevel);
                if (Application.loadedLevel != loadLevel)
                    Application.LoadLevel(loadLevel);
            }
        }

The next stage is to plug this into Unity. I put the following in a Master Script (which is essentially just a script associated with an empty game object).

    void OnApplicationQuit()
    {
        GameState.SaveGameState();       
    }

    void Start()
    {
        GameState.LoadGameState();
    }

I’ve seen plenty of articles on using serialisation for this, and that would obviously have the same effect, but this is another option.

Using inheritance in Unity for better code re-use

In previous posts regarding Unity, I’ve made the comment that I’m quite new to Unity… but I’m not new to C#, and have been a little surprised regarding the apparent lack of code re-use through inheritance and polymorphism in scripting examples that I’ve seen. So much so, that I started to assume that, for some reason, this wasn’t possible in Unity.

It is. I was looking for an architecture like this:

UnityArchitecture

As an experiment, I created a base script:

public class BaseScript : MonoBehaviour
{
    public virtual void RunStart() { }
    public virtual void RunUpdate() { }

    void Start ()
    {
        RunStart();
    }
	
    void Update ()
    {
        RunUpdate();
    }

    void OnCollisionEnter(Collision collision)
    {
        StandardCollision(collision);
    }

You get the idea. I handle the standard functions, and then provide either some default functionality, or none, and allow the child to override. Inherit as you would for any base class:

public class MyScript : BaseScript
{
    public override void RunStart()
    {
        base.RunStart();

As you would expect from any C# / .NET similar structure, you reference in the child script, and you get the base functionality.

Playing a longer running animation in Unity

Continuing on with my list of things that I’ve found in unity (I’m using 5, but have no reason to believe these wouldn’t work for 4), I had cause to execute an attack animation in a character. For reference, the character I’ve been using is here

So far, when playing an animation, I’ve used something similar to this:

gameObject.GetComponent<Animation>().Play("Idle_2");

In fact, if you put that in the Update of the linked object, you’ll get an angry looking chap looking like he’s about to charge. In order to plumb in the attack, it’s necessary to cache the animation. Start with a class level variable:

private Animation _animation;

Then, inside the update statement, something similar to this:

void Update ()
{
    if (_animation != null && _animation.IsPlaying("Attack_1")) return;

    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (_animation == null)
            _animation = gameObject.GetComponent<Animation>();
        _animation.Play("Attack_1");            
    }
}

One of the bizarre things that I learnt about unity while doing this, was that if you have a null reference, it doesn’t crash. It doesn’t work, but it doesn’t crash.

I find this annoying.

Working with the threading system in Unity

Unity seems to have a multi-threaded system, but I could find no way of accessing the dispatcher. Consequently, it’s necessary to create some kind of self-rolled task queue. The specific problem that I faced was with using the timer; here’s the code for the timer:

public class MasterScript : MonoBehaviour
{
    private Timer _timer;

    void Start ()
    {
        _timer = new Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += _timer_Elapsed;
        _timer.Start();
    }

    private void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        SpawnNewObject();
    }
}

The idea being that every second, and new object would appear on the screen. However, as soon as you run this, it crashes (or as close as Unity comes to crashing):

FindGameObjectWithTag can only be called from the main thread

The solution that I came up with was as follows:

public class MasterScript : MonoBehaviour
{
    public static Queue<Action> TaskQueue;

    private void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        SpawnNewObject();
    }

    private void SpawnNewObject()
    {
        TaskQueue.Enqueue(() =>
        {
            var newObj = Instantiate<GameObject>(MyObject);

Then, simply change the Update function to run them:

    void Update ()
    {
        if (TaskQueue.Count > 0)
        {
            TaskQueue.Dequeue().Invoke();
        }
    }

I’ve used the idea of a “Master Script” to deal with the queue, and this can be queued to from somewhere else in the game, which makes it more flexible.

Advancing to the next Level in Unity

I’m quite new to Unity, and so thought I would start blogging useful things that I’ve discovered. Obviously, there is the which is basically where all this information comes from, and also an excellent tutorial on YouTube. I found this after trying a Pluralsight course on Unity, but rapidly losing the will to live while watching it.

In my particular example, I have a game, whereby touching a specific object progresses to the next level. Here’s the code (against the target object):

    void OnCollisionEnter()
    {
        if (Application.loadedLevel < Application.levelCount)
            Application.LoadLevel(Application.loadedLevel + 1);
        
    }

I admit, it’s not exactly rocket science, but it took me a while to work this out. I spent some time trying to parse the level name, and other workarounds, before I spotted that it’s all in the Application object.