- Home /
I want to increase the health bar when I press a button.
Hi, I am a beginner in unity and I have this code that makes the health bar goes down with time and I don't know how to make it refill when i press a button (UI Image ) without changing the code. thanks for answering all help is appreciated.
Answer by as30050273 · Aug 13, 2017 at 09:27 AM
In Update() add this:
if(Input.GetKeyDown(KeyCode.R)){ playerHealth = 1; bar.fillAmount = playerHealth; }
Hi,I am making my game for android so I'm using buttons (on click) @as30050273
Answer by carlos170586001500 · Aug 14, 2017 at 06:07 AM
if(Input.GetKeyDown(KeyCode.Space)){
//Your Code
//https://docs.unity3d.com/ScriptReference/KeyCode.html
}
OR
if(Input.GetKeyDown("space")){
//Your Code
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
}
Or with buttons:
public class TaskIcon : MonoBehaviour,IPointerClickHandler{
public float Health;
public void OnPointerClick(PointerEventData eventData){
//code
}
}
Or with the UI Component Button https://docs.unity3d.com/ScriptReference/UI.Button.html
Should I put it on Health bar or on the button I did it on the button but I can't call or enter the health bar script, can you explain what you did if you please.
@carlos170586001500
Its pretty simple: Create a Button (GameObject Tab ->UI -> Button)
Add an new script to the button: using UnityEngine; using UnityEngine.EventSystems; public class NewButton: $$anonymous$$onoBehaviour,IPointerClickHandler{ public PlayerBar1 PlayerBar1; public void OnPointerClick(PointerEventData eventData){ Debug.Log("OnPointerClick Event: Health Bar"); PlayerBar1.ResetHealth(1f); } }
Add to PlayerBar1 Script the ResetHealth function: public void ResetHealth(float h){ Debug.Log("ResetHealth Function"); bar.fillAmount=h; playerHealth =h; }
Test the script and press the button, if you see in Console "OnPointerClick Event: Health Bar" the button work.