Help with GetComponent

This is using the Unity Engine.
I have 3 scripts related to this problem. One is attached to a temporary game object that when the player collides with it, sends a message to the player Damage Controller. The player Damage Controller updates the health inside of the player’s Damage Controller script. Using Debug.Log, I can see that the player health updates as expected.

The third script is a component of a GUI Texture. From inside of the GUITexture script, I try to GetComponent of the Damage Controller.health. But running a Debug inside of the GUITexture script, for some reason the GetComponent.health is not updating as expected and is why my health status GUI Texture is not changing inside the game scene. Any help will be great.

using UnityEngine;
using System.Collections;
public class Trap: MonoBehaviour 
{
	//Trap intrinsic properties
	public int damage = 1;

	void OnTriggerEnter(Collider other) 
	{
		if(other.tag == "Player" || other.tag == "Enemy")
		{	
			//Debug.Log("Collision with Player Object!");
			other.collider.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
			//this.SendMessage("SetGUITexture");
			Destroy(gameObject);
		}
	}
} 

using UnityEngine;
using System.Collections;
public class DamageController : MonoBehaviour 
{
	public int         health = 4;

	public void ApplyDamage(int damage)
	{
		health -= damage;
		Debug.Log("Updated Health is: "+health);

		if(health == 0)
		{
			Destroy(gameObject);
		}
	}
}

using UnityEngine;
using System.Collections;
public class HealthGUI : DamageController
//public class HealthGUI : MonoBehaviour 
{

	public int healthGUI = 4;
	public DamageController damageController;
	private GameObject playerGameObject;

	// Use this for initialization
	void Start () 
	{
		playerGameObject = GameObject.FindGameObjectWithTag("Player");
	}
	
	// Update is called once per frame
	void Update () 
	{
		DamageController damageController = playerGameObject.GetComponent<DamageController>();
		healthGUI = damageController.health;
		Debug.Log("Health is  : "+healthGUI);
	}
}

Ok, figured it out. The root of the problem stems from your double use of the tag “Player”. Throughout your code, you are thinking of the parent, “PFB_PlayerCar”, and the child/collider, “PlayerMesh”, as the same thing, and mixing them up. You need to have only one object tagged “Player”.

The specific bug here is because both “PFB_PlayerCar” and “PlayerMesh” have a “DamageController” component. In your OnTriggerEnter, you are calling SendMessage on the collider object, “PlayerMesh”, and modifying that health. So, remove “DamageController” from “PlayerMesh”, and then change trigger line to be:

other.collider.transform.parent.SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);

Good luck :slight_smile: