- Home /
Public Health Var C#
I'm new to coding, and trying to build a very very basic health system with NGUI and Unity. For the moment I'm trying just trying to get the Progress Bar to update the current HP I have on the player, which I have as an int. I have 2 separate codes, 1 on the gui, and 1 on the player which I'll add damage to, etc. For the moment I'm just trying to link them and having issues figuring it out.
I know this is very bad, but I'm trying to learn, not copy/paste. So far I have this.
PlayerHealth (attacked to player)
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
private int maxHealth = 300;
public float Health;
// Use this for initialization
void Start () {
Health = maxHealth;
}
// Update is called once per frame
void Update () {
}
}
gui code
using UnityEngine;
using System.Collections;
public class VitalBarBasic : MonoBehaviour {
private UISlider _slider;
private float _maxWidth;
private float _health;
void Awake() {
_slider = GetComponent<UISlider>();
_maxWidth = _slider.foreground.localScale.x;
}
void Start() {
_slider = GetComponent<UISlider>();
_health = Player.GetComponet<Health>();
}
public void Update() {
_slider.sliderValue = _health/30;
}
public void UpdateDisplay( float x ) {
_slider.sliderValue = x;
}
}
Answer by MiniDemonic · Sep 25, 2012 at 06:23 AM
You can use the SendMessage function, look it up on the unity documentation page. http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html
Add a GameObject variable in the GUI script and put your player GameObject in it, create a function in the player script let's call it AlterHealth.
Here is a really simple code for it.
void AlterHealth(int newHealth){
health = newHealth;
}
In the GUI script use this code.
playerGO.SendMessage("AlterHealth", value);
This will send a message to the player GameObject and execute the function AlterHealth and change the players health to whatever integer value contains.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Changing Mesh of an object depending on Health Value. C# 2 Answers
Distribute terrain in zones 3 Answers
Problem with circular health bars 0 Answers
NGUI- Adding children under UIDraggable panel at runtime 1 Answer