Skip to content

Instantly share code, notes, and snippets.

@nevernotsean
Last active July 23, 2020 19:22
Show Gist options
  • Save nevernotsean/4c26fcd8d9d436f4a1d2e3325ef169d8 to your computer and use it in GitHub Desktop.
Save nevernotsean/4c26fcd8d9d436f4a1d2e3325ef169d8 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityAtoms.BaseAtoms;
public class UnityAtoms_UI_Hearts_Bar : MonoBehaviour
{
[SerializeField] private FloatVariable _Value;
public float Value { set { _Value.Value = value; } get { return _Value.Value; } }
[SerializeField] private FloatVariable _MaxValue;
public float MaxValue { set { _MaxValue.Value = value; } get { return _MaxValue.Value; } }
public GameObject UnitPrefab;
public Vector3 spacing;
List<GameObject> Units;
[Header ("Properties")]
bool initOnAwake;
private void Awake ()
{
Units = new List<GameObject> ();
if (initOnAwake)
Value = MaxValue;
_Value.Changed.Register (Handle_ValueUpdate);
_MaxValue.Changed.Register (Handle_MaxValueUpdate);
// these aren't needed if you toggle on the "Trigger Event on OnEnable" property of the atom.
// Handle_ValueUpdate (Value);
// Handle_MaxValueUpdate (MaxValue);
}
void Handle_ValueUpdate (float val)
{
for (int i = 0; i < Units.Count; i++)
{
if (i < val)
Units[i].SetActive (true);
else
Units[i].SetActive (false);
}
}
void Handle_MaxValueUpdate (float val)
{
for (int i = Units.Count; i < Mathf.CeilToInt (val); i++)
{
var item = Instantiate (UnitPrefab, transform.position + (spacing * i), Quaternion.identity, transform);
item.TryGetComponent<SpriteRenderer> (out SpriteRenderer sprite);
sprite.sortingOrder = i;
Units.Add (item);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment