I’ve looked at dozens of tutorials and posts around here, but I simply cannot wrap my head around how GetComponent works and I’m beginning to lose my mind. I have two scripts, one called PlayerHealth and one called HealthBarScript. I need to access the health variable from PlayerHealth and use it to control the fill amount of a sprite in HealthBarScript. Nothing I’ve tried has worked. If somebody could break it down super simply for me it would be much appreciated. Also, I am an absolute beginner so sorry if my code looks like trash.
PlayerHealth -
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class PlayerHealth : MonoBehaviour {
public static int health = 100;
public AudioSource playerAudio;
public AudioClip GameOver;
private bool deathDone;
// Use this for initialization
void Start () {
playerAudio = GetComponent<AudioSource>();
health = 100;
deathDone = false;
}
// Update is called once per frame
void Update ()
{
if (health <=0 && !deathDone)
{
health = 0;
Debug.Log ("Mission Failed.");
playerAudio.PlayOneShot (GameOver, 1.0f);
deathDone = true;
}
}
// If the player hits a KillBox
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "KillBox")
{
health = 0;
}
if (coll.gameObject.tag == "EnemyProjectile")
{
health -= 10;
}
}
}
HealthBarScript -
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HealthBarScript : MonoBehaviour {
public GameObject player;
public Image HealthSprite;
// Use this for initialization
void Start ()
{
GameObject thePlayer = GameObject.Find("thePlayer");
PlayerHealth health = player.GetComponent<PlayerHealth>;
HealthSprite = GetComponent<Image>();
}
// Update is called once per frame
void Update ()
{
HealthSprite.fillAmount = PlayerHealth.health/360;
}
}