Skip to main content

Binding UI at Runtime

For GameObjects instantiated at runtime that need to be bound to UI, you can bind Vitals Components to UI at runtime through script.

This is useful when instantiating multiple instances of a prefab, because having a Vitals Hook assigned on the prefab means that all instances will be sharing that hook.

Basic Usage

Setup a UI element with the Vitals UI Bind component. This could be on the prefab or in the scene.

Leave the Vitals Hook field empty, and tick the Bound Through Code box ( this stops the component from debugging that a hook does not exist).

UI Bind Component without Hook

Now when you instantiate your prefab with a Vitals Component you can use the Vitals Utility's Bind function. This is done by getting a reference to both the Vitals Component and the Vitals UI Bind Component, and passing them as parameters.

// In this example the UI element is on the enemy prefab
[SerializedField] private GameObject enemyPrefab

private void SpawnEnemy(Vector3 position){

var enemy = Instantiate(enemyPrefab, position, Quaternion.identity);

var enemyHealth = enemy.GetComponent<Health>();

var uiBind = enemy.GetComponent<VitalsUIBind>();

VitalsUtility.Bind(health, uiBind);
}

To see an example of this, check out the EnemyDemoScene.