Tag: game architecture

Refactoring UI Elements

Refactoring UI Elements

I started this post with just the reference pic above almost 6 weeks ago, so I’ve been trying to remember exactly what I was trying to tell myself here. Fortunately for me I did annotate the code so I’ve managed to backtrack and figure things out.

As with many posts during a period of review and testing this is again about extensibility, reusability and ease of use.

The issue was with the size of the UI prefab – it had become a bit of a goliath with many interdependent elements (objects) being controlled via the centralised UI controller class. This meant that the the UI was a pain to instantiate in a scene as the references were difficult to ‘find’ and were so interwoven with one another that any bug tracking or recycling/repurposing was getting to be a bit of a chore. What I’m always after is rapid prototyping and that means trying to make things that are for the most part drag and drop.

I’ve read so many times across the Unity fora about the importance of keeping things as simple and independent as possible – I think I’ve written a lot about it too – but as ever the best teacher is failure and thats exactly what my giant prefab brought to the fore.

So as of this last iteration of the UI, all child elements are separated out into their own classes and are saved as individual prefabs. This has simplified matters and allowed the whole thing to be come more extensible and flexible in terms of functionality:

Overview of the UI elements

This new arrangement of prefabs can now be used in a modular way and new elements should be able to be introduced with a minimum of fuss as everything is pretty much separate, with each element of the UI existing as its own class containing its own functions that can be referenced and called from anywhere or anything else.

For example, the prefab element called BroadcastMessages contains:

  • its own class
  • a text (TMP) object
  • a background object
  • an animator component

The class itself becomes very simple to manage as its functionality applies only to its children. This functionality is accessed as a function that displays (and animates) incoming text addressed to that function from elsewhere by calling:


public class BroadCastMessages : MonoBehaviour
    TMP_Text broadcastMessages_Text;
    Animator animator_broadcastMessages;

    void Start()
        broadcastMessages_Text = GetComponentInChildren<TMP_Text>();
        animator_broadcastMessages = GetComponentInChildren<Animator>();
        broadcastMessages_Text.enabled = false;

    //public method for receiving messages:
    public void IncomingBroadcastMessages(string message)
        broadcastMessages_Text.text = message;

        if (broadcastMessages_Text.text != null)
            broadcastMessages_Text.enabled = true;
            animator_broadcastMessages.SetBool("broadcastMessage_FadeUp", true);

        if (broadcastMessages_Text.text == null)
            animator_broadcastMessages.SetBool("broadcastMessage_FadeUp", false);
            broadcastMessages_Text.enabled = false;

The upshot of this is that the UI is now a system of prefab elements responsible (in the main) for their own part of the display using no more that 30-40 lines of code:

Outline of UI structure using individual prefabs with individual classes

The only complication/extension in the display I am currently using is the ScreenToWorldPoint method (outlined in this post) that displays a line linking information boxes to specific objects identified and passed from the raycast function in PlayerInteraction(). This display method can be seen in the screen grab at the top of this post.

The information (text) is passed from the raycast hit object to either the RHS or LHS messages class (depending on the objects’ tag).

The information is then displayed using the ScreenToWorldPoint method which I have now simplified by moving into the class UI_Manager – the same function is called by both the RHS and LHS Messages classes so this saves duplication:

public class UI_Manager : MonoBehaviour

    public void FadeUpLineRenderer(LineRenderer lineRenderer, Transform rayHitTransform,
        TMP_Text text)
        //Fade up and link text to the object in world space

    public void FadeDownLineRenderer(LineRenderer lineRenderer, TMP_Text text)
        if (alpha_lineRenderer > 0)
            //Fade down

So this class (UI_manager) gets called by either LHS of RHS messages which provide references to a lineRederer, a Transform and the text. The LHS/RHS messages are accessed themselves using a unique function.

The snippet below is from the LHS_messages class. Its is a slightly more complex version of the Broadcast Messages class but basic functionality is the same – messages are passed to it using the call:


Then the appropriate elements are passed to the function in UI_Manager:




public class LHS_Messages : MonoBehaviour

//Incoming messages public method
    public void IncomingMessages(string message)
        LHS_messageText.text = message;

    void Update()
        //If no raycast hits turn off the displays
        if (playerInteraction.rayCastHitObject == null)
                //fade down UI window
                LHS_messageAnimator.SetBool("LHS_Panel_FadeUp", false);

                //set the rayHitTransform to null
                rayHitTransform = null;

                //Fade Down LineRenderer:
                uI_Manager.FadeDownLineRenderer(lineRenderer, LHS_messageText);

        //if raycast hit display if tag is "Interactable"
        if (playerInteraction.rayCastHitObject != null
            && playerInteraction.rayCastHitObject.CompareTag("Interactable"))
            //turn on this element
            LHS_messageText.enabled = true;
            lineRenderer.enabled = true;

            //Fade up via Animator
            LHS_messageAnimator.SetBool("LHS_Panel_FadeUp", true);

            // set up the generic Transform component:
            rayHitTransform = playerInteraction.rayCastHitObject;

            //ADD THE LINE
            uI_Manager.FadeUpLineRenderer(lineRenderer, rayHitTransform,

Summing up what this approach and refactoring has helped achieve is a more extensible, easier to track/debug and generally much more flexible series of prefabs/classes that can be adapted, reused, repurposed and rewritten as circumstances require.

For example the UI_Manager class is now nothing more complex than an extra function holder that can be logically extended to include and execute any repeated functions that occur within the UI as a whole – I do believe I’m not far away form understanding Properties here so no doubt at some point down the line I’ll have an Aha! moment and write a new post referencing and ridiculing my clumsiness in this one….

That plus perhaps a more important point for me – by trying to employ a more sensible, simplified approach to writing the code in the first place I’m able to come back after a complete absence of some 6 weeks and take only 20 minutes or so to see what I’m doing.

Knowing what I’m trying to do is mostly a good thing…..leaving easy to read comments is definitely a good thing.

Better Referencing in Unity

Better Referencing in Unity

After several months of development trying to keep things as simple as possible has become increasingly important.

With only a few elements on the game sandbox its sometimes been a struggle to quickly iterate and change functionality without breaking relationships and spending hours trawling through the code trying to find bugs and/or having to reattach or redefine references.

In my recent elevator script development this took an extreme turn as the relationships between objects became overly complex and lacking centralised control, so I spent some time looking at ways to simplify the process.

Component references:

Having to constantly drag and drop game object and component references into the script window, the following methods have proved to be useful:

void Start()
            //Cache references in Start() to save memory:

            //get component attached to this game object:
            component = GetComponent<Type>();

            lineRenderer = GetComponent<LineRenderer>();

            //Using the Find method is useful to search the scene but can eventually lead to performance issues
            //so used by caching reference and assigned in Start()

            reference = Type.Find("Name");

            //this can be use in tandem with GetComponent:
            //example from the UI:
            //GET THE GO and derive elements from that:
            LHS_messageObject = GameObject.Find("LHS_Messages");

            //Attached components:
            LHS_messageRectTransform = LHS_messageObject.GetComponent<RectTransform>();
            LHS_messageText = LHS_messageObject.GetComponent<TMP_Text>();
            LHS_messageAnimator = LHS_messageObject.GetComponent<Animator>();

             //Find of Type:
            //This method is useful for finding specific components by type
            //like other classes:

            reference = Component.FindObjectOfType<Type>();

            //example grabbing the player interaction class in the UI:
            playerInteraction = GameObject.FindObjectOfType<PlayerInteraction>();

These methods have been useful in referencing objects/classes and when used in tandem with arrays have proved themselves useful in quickly creating and editing core functionality of the controller class.

        //example using arrays of components:         
        elevatorMechanics = GameObject.FindObjectOfType<ElevatorMechanics>();

        doors = new Transform[elevatorMechanics.numStoreysInThisBuilding];
        doorAnimators = new Animator[elevatorMechanics.numStoreysInThisBuilding];
        doorIsOpen = new bool[elevatorMechanics.numStoreysInThisBuilding];

        for (int i = 0; i < elevatorMechanics.numStoreysInThisBuilding; i++)
            if (transform.GetChild(i).name.Contains("Placeholder"))
                doors[i] = transform.GetChild(i);
                doorAnimators[i] = doors[i].GetComponentInChildren<Animator>();
                doorIsOpen[i] = false;

Saying that, its important to mention (again) that having a centralised point (object/class) within the hierarchy that deals with all the ‘thinking’ of the structure is massively important. Using this approach during the elevator development I was able to cut down hundreds of lines of code across 5 classes to less that 50 lines across 4 of the attached scripts (dealing with individual functions like the buttons control panel, call buttons, triggers and doors) plus a longer ‘controller’ class that deals with the core mechanics of moving, UI, calculating floors and triggering events.

In this hierarchical structure the controller class is ‘aware’ of its own immediate environment in terms of how it should be affected in the world plus a deeper awareness of its children – doors, platform, buttons etc.

In turn, the child elements are aware of nothing except their own functionality and pass that functionality on to the controller class.

As a final note on referencing now that I’ve veered off into architecture, this post is worth mentioning as an extension method for finding objects within a hierarchy structure: https://answers.unity.com/questions/183649/how-to-find-a-child-gameobject-by-name.html

GameObject GetChildWithName(GameObject obj, string name) {
     Transform trans = obj.transform;
     Transform childTrans = trans. Find(name);
     if (childTrans != null) {
         return childTrans.gameObject;
     } else {
         return null;