I’m making a topdown shooter that has UI healthbars that follow the player and enemies. Each healthbar is a child of a canvas, which is a child of the player/enemy the healthbar follows. The script works perfectly, except when I reload the scene. When this happens, the healthbar that follows the player jitters around, while the healthbars following the enemies work fine. What is my issue here?
Script for my health bars:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
private Transform target;
private float yOffset;
private Vector3 offset;
private float rotationOffset;
private Vector3 rotationOffsetVector;
private Image healthBar;
private Camera mainC;
// Start is called before the first frame update
void Start()
{
mainC = Camera.main;
target = transform.parent.parent;
yOffset = 25f;
offset = new Vector3(0, yOffset, 0);
healthBar = gameObject.transform.GetChild(1).GetComponent<Image>();
transform.position = target.position;
}
// Update is called once per frame
void Update()
{
rotationOffset = Mathf.Clamp(Mathf.Abs(1 / target.rotation.z) * 2.5f, 0, 15f);
rotationOffsetVector = new Vector3(0, rotationOffset, 0);
transform.position = mainC.WorldToScreenPoint(target.position) + offset + rotationOffsetVector;
}
public void setHealthBar(float health, float maxHealth)
{
healthBar.fillAmount = health / maxHealth;
}
public void hideHealthBar()
{
Destroy(gameObject);
}
}