I need quick help with my C# code GetComponent!
Im making a health bar and I wanted to make the fill amount of the image the same as my Health value in my Enemyscripts script within my Enemy object. For some reason Unity doesnt recognize my code. I need help please! C# code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Health_bar : MonoBehaviour {
public GameObject Enemy;
// Update is called once per frame
void Update () {
Image image = GetComponent< Image >();
image.fillAmount = Enemy.GetComponent<Enemyscripts>().Health;
}
}
Enemyscripts code here:
#pragma strict
public var Health : float = 100f;
function Start () {
}
function Update () {
if (Health == 0.0) {
Destroy(gameObject);
}
}
function RemoveHealth () {
Health--;
Debug.Log(Health);
}
Answer by MakinStuffLookGood · Nov 20, 2015 at 08:05 PM
Avoid mixing C# and Javascript. Here's your Enemyscripts component rewritten in C#:
using UnityEngine;
using System.Collections;
public class Enemyscripts : MonoBehaviour {
public float Health = 100f;
void Start () { }
void Update () {
if (Health <= 0) {
Destroy(gameObject);
}
}
void RemoveHealth () {
Health--;
Debug.Log(Health);
}
}
I would opt to write everything in C# if I were you. Most other users will give the same advice. I also changed your float equality check to a less-than-or-equal. Never compare exact floats like that, you may end up with float point inaccuracies that cause the if statement to never be true.
Your answer
Follow this Question
Related Questions
GetComponent is not a member of Object 0 Answers
Store script from GetComponent ? 1 Answer
How do I run an animation then destroy a game object? 1 Answer
GameObject changes to None in inspector after pressing Play 0 Answers
How to enable and disable a script on an game object by pressing a keyboard button? 1 Answer