The unitypackage can be downloaded from here.

The demo

Introduction

The purpose of this example is to show how energy bars can be attached to infinite (in theory) number of game objects on the scene. The entire example is written in JavaScript, but it should be no problem to understand the code by C# developers.

There are at least two methods to anchor Energy Bar Toolkit bars to world objects. Both have advantages and disadvantages, but the Anchor approach is more difficult if you’re planing to instantiate your game objects dynamically. Here you will learn how to do it.

Know How

First let’s take a look on what we have.

There is a bar object that is simple and elegant enough to describe health of bots.

This bar has been created like this:

Then when prefab has been created it is no longer available in the example scene, but in Prefabs directory:

Instancing

To properly instantiate bot with a bar attached I needed to instantiate two prefabs:

  • botWithoutBar
  • healthBar

The second one is the MadAnchor and it needed further setup to be anchored to newly instantiated bot. The secret is to assign new bot object to the anchor, so the anchor will follow. Here’s the code snippet from the spawner script:

// health bar prefab is an anchor and have bar as its child
var anchor = Instantiate(healthBar).GetComponent(EnergyBarToolkit.MadAnchor);
anchor.transform.parent = panel.transform;

// position and scale can be distorted at that point
anchor.transform.localScale = Vector3(1, 1, 1);
anchor.transform.localPosition = Vector3.zero;

// make the anchor follow the bot game object
anchor.anchorObject = bot.gameObject;

Taking the energy

Next difficulty was how to communicate from JavaScript with attached bar (which is written in C#). To do that I’ve used method from the docs:

function Hit() {
    health -= hitPower;
    healthBar.BroadcastMessage("SetValueF", health);
    
    if (health <= 0) {
        Explode();
    }
}

Included file info.html not found in _includes directory

Destroying

When bot is destroyed the anchor with bar is needed to be destroyed as well. Bot have the anchor set as healthBar field, so it is destroyed in OnDestroy() method.

function OnDestroy() {
	Destroy(healthBar.gameObject);
}