Tag Archives: Unity

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.

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.

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.