How to create a link between HealthScript and HealtBar script ?
Hi everyone!
The thing I would like to do is that when my health points' player go down, its health bar goes down too. But I don't know how can I do. Maybe something like create a "link" between these two scripts...? I'm novice in scripting...
These are my HealthScript and my HealthBar script:
using UnityEngine;
public class HealthScript : MonoBehaviour {
public int hp = 5;
public bool isEnemy = true;
void OnTriggerEnter2D(Collider2D collider)
{
ShotScript shot = collider.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
if (shot.isEnemyShot != isEnemy)
{
hp -= shot.damage;
Destroy(shot.gameObject);
if (hp <= 0)
{
Destroy(gameObject);
}
}
}
}
}
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI;
public class HealthBar : MonoBehaviour {
#region Attributes
public GameObject healthBar;
public Color goodColor;
public Color middleColor;
public Color badColor;
#endregion
#region Unity methods
void Start()
{
SetColor();
}
#endregion
#region Other methods
public void SetDamages(float value)
{
healthBar.GetComponent<Scrollbar>().size -= value;
float totalValue = healthBar.GetComponent<Scrollbar>().size;
SetColor(totalValue);
}
void SetColor(float value = 1)
{
if(value >= 0.5f)
{
healthBar.transform.FindChild("Mask").FindChild("Sprite").GetComponent<Image>().color = goodColor;
}
else if(value >= 0.25f && value < 0.5f)
{
healthBar.transform.FindChild("Mask").FindChild("Sprite").GetComponent<Image>().color = middleColor;
}
else
{
healthBar.transform.FindChild("Mask").FindChild("Sprite").GetComponent<Image>().color = badColor;
}
}
#endregion
}
Could someone help me please? :)
Answer by JedBeryll · May 14, 2016 at 01:34 PM
Create a variable for the health bar in the HealthScript like this:
public HealthBar healthBar;
Then assign it in the inspector.
if (hp <= 0)
{
Destroy(healthBar.gameObject);
Destroy(gameObject);
}
I created the variable in the HealthScript, and now you say that I must assign this script in the inspector of the health bar?
No, you have the variable in the HealthScript so drag and drop your healthBar gameObject into your HealthScript's variable.
The thing is that I can't drag and drop nothing in my HealthScript's variable... No prefab, no gameobject, nothing (as you can see in the photo ) ^^' Did I make a mistake somewhere?
Your answer
Follow this Question
Related Questions
i have no clue what is wrong with the script (help) 1 Answer
Annoying Quaternions and Eulers 1 Answer
Why does my start function not work? 1 Answer
How to make low health vignette? 0 Answers