NGUI Health SendMessage Has No Receiver

Hi, I’m trying to make a very simple way to pass the health of the player to ngui as a float and adjust the hp bar. The health of the player seems to work, as does adding a float manually to ngui changes the size of the life bar but I can’t seem to figure out how to connect the two to check on its own.

I have this script PlayerHealth.cs
using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
 
 private int maxHealth = 300;
 public int health;
 
 // Use this for initialization
 void Start () {
 health = maxHealth;
 }
 
 // Update is called once per frame
 void Update () {
 gameObject.SendMessage("AlterHealth", .5f);
 }
}

And I have this as VitalBarBasic.cs
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() {   
 }   
 public void Update() {  
 _slider.sliderValue = _health;
 }
       
 public void UpdateDisplay( float x ) {
 _slider.sliderValue = x;   
 }

 public void AlterHealth(int newHealth){
 _health = newHealth;
 }

}

I don’t think I have the script actually looking in the right place but I’m a little confused how to structure the “sendmessage”
Thanks for any help.

First. It is not recommended to use SendMessage every frame (Update, LateUpdate, FixedUpdate), it is slower that normal method call. Until you understand more, I recommend avoid SendMessage.

In your code what you are doing is calling asynchronously the method “AlterHealth” of all Components (reference) owned by the game object that owns your script PlayerHealth.

If VitalBarBasic is attached into the same gameObject that PlayerHealth, it should work. If you have 2 gameObjects, you must send a message into another gameObject.

Add a new variable “public VitalBarBasic bar;” into PlayerHealth and resolve its reference in the editor. Then, change your Update to:

// asynchronously call AlterHealth into all bar.gameObject components
bar.gameObject.SendMessage("AlterHealth", .5f);

or

// direct call 
bar.AlterHealth(5);