Tag Archives: MonoBehaviour

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:

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.