Thanks @matt_c! Do you remember your score?
I used this tutorial for health bars. I think it should be possible to create just one script/class but I couldn’t do it so instead I created 3 separate classes for player, bosses and shield. The code is simple, what’s not so obvious is how to attach script to gameobject and slider. If you follow the tutorial you should be able to do it. The border is optional, I used it only for the player’s bar.
The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Slider healthBar;
public player playerHealth;
// Start is called before the first frame update
void Start()
{
// if statement to avoid error when player dies.
if (!playerHealth) { return; }
playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<player>();
healthBar = GetComponent<Slider>();
healthBar.maxValue = playerHealth.maxHealth;
healthBar.value = playerHealth.maxHealth;
}
public void SetHealth(float hp)
{
if (!playerHealth) { return; }
healthBar.value = hp;
}
}
The power ups are spawned in similar way as enemies with EnemySpawner
. Bonuses have their own layer so you can decide who can pick them up. The exception is laser upgrade which tries to access a variable that only Player
has so to avoid errors only the player can pick it up.
The code for bonus spawner:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BonusSpawner : MonoBehaviour
{
[SerializeField] float timeBetweenBonus = 5f;
[SerializeField] List<GameObject> bonusTypes;
//[SerializeField] GameObject bonusType;
[SerializeField] float bonusFallSpeed = 2f;
[SerializeField] float spawnLocation = 1f;
float waitCounter;
// Start is called before the first frame update
void Start()
{
waitCounter = timeBetweenBonus;
}
// Update is called once per frame
void Update()
{
waitCounter -= Time.deltaTime;
if (waitCounter <= 0f)
{
int randomIndex = Random.Range(0, bonusTypes.Count);
float offset = Random.Range(-spawnLocation, spawnLocation);
GameObject bonus = Instantiate(bonusTypes[randomIndex], transform.position + new Vector3(offset, 0, 0), Quaternion.identity) as GameObject;
bonus.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -bonusFallSpeed);
waitCounter = timeBetweenBonus;
}
}
}
Variable spawnLocation
is used to randomise the x
position of bonus gameobject spawning.
List<GameObject> bonusTypes
should be populated with bonus prefabs in Unity Editor. The easiest bonus that I could think of is the health pack which is simply a gameobject with a DamageDealer
component with negative damage value. Allies work in the same way as enemies (they use Enemy.cs
component and WaveConfig
mechanism) but have separate layer for the collision matrix.
Let me know if you are interested in particular bonus type.