Using C# in Unity 5.6…
I have an Object ‘player’ who creates an Image ‘healthBar’ to the Canvas. I can sucessfully change ‘healthBar’ scale, and have it’s position move with ‘player’. But when I wish for ‘player’ to die ‘healthbar’ stays in the canvas. I can’t get it’s correct InstanceID to destroy the correct ‘healthbar’ in the Canvas…
I only posted relevant code
What am I doing wrong, or what should I be doing?
public class Player : MonoBehaviour {
public Canvas canvas;
private Image createHealthbar;
public Image healthBarImage;
private Image healthBar;
private Image createHealth;
public Image healthImage;
private Image health;
void Start(){
pixelX = canvas.worldCamera.pixelWidth;
pixelY = canvas.worldCamera.pixelHeight;
}
void Update(){
if (AmSelected == true) { IsSelected (); }
if (Input.GetKeyUp (KeyCode.H)) {
if (health.transform.localScale.x > 0.05f) {
health.transform.localScale -= new Vector3 (.1f, 0f, 0f);
health.transform.localPosition -= new Vector3 (5f, 0f, 0f);
} else {
//Destroy (createHealthbar); //These don't work...
//Destroy (createHealth); //These don't work...
Destroy(gameObject); //Player destroys but healthbars remain...
}
}
}
void IsSelected(){
if (healthBar != null) {
Vector3 screenPos = Camera.main.WorldToScreenPoint (this.transform.position + heightOffset);
healthBar.transform.localPosition = (new Vector3 (screenPos.x - (pixelX / 2f), screenPos.y - (pixelY / 2f), 0f));
Debug.Log ("itID " + healthBar.GetInstanceID());
//Debug shows a different ID, no matter which (healthBarImage, createHealthbar, healthBar) I use...
} else {
createHealthbar = Instantiate(healthBarImage, canvas.transform) as Image;
healthBar = createHealthbar;
createHealth = Instantiate (healthImage, createHealthbar.transform);
health = createHealth;
}
}
}