- Home /
Adding score when enemy dies (Errors)
Hi, I have the following 2 codes:
Enemy Health:
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
public float health = 10.0f;
public float score = 0f;
public void Damage( float amt ) {
health -= amt;
if(health <= 0) {
Die();
score++;
}
}
void Die() {
Destroy (gameObject);
}
}
Score:
using UnityEngine;
using System.Collections;
public class Score : MonoBehaviour {
public void OnGUI()
{
GUI.color = Color.red;
GUI.Label(new Rect(10, 30, 60, 20), "Score: " + EnemyHealth.score);
}
}
and I get the following errors:
Assets/Standard Assets/Scripts/Score.cs(9,12): error CS1503: Argument
#2' cannot convert
object' expression to typestring' 2. Assets/Standard Assets/Scripts/Score.cs(9,12): error CS1502: The best overloaded method match for
UnityEngine.GUI.Label(UnityEngine.Rect, string)' has some invalid argumentsAssets/Standard Assets/Scripts/Score.cs(9,68): error CS0120: An object reference is required to access non-static member `EnemyHealth.score'
What am I doing wrong? I know I have to make it public but how do I go about doing this? Thanks
Answer by YoungDeveloper · Aug 18, 2013 at 04:10 PM
public void OnGUI()
{
string text = "Score: "+EnemyHealth.score;
GUI.color = Color.red;
GUI.Label(new Rect(10, 30, 60, 20), text);
}
Answer by aldonaletto · Aug 18, 2013 at 04:17 PM
score is a member variable: it exists in each EnemyHealth script instance, thus you must specify which instance you want to access. But there are other flaws in this code: 1) if you have several enemies, all their scores will be rendered at the same position, thus only the one rendered last will be visible; 2) being a member variable, score will die with the enemy, thus incrementing it is pointless.
If you have only one enemy alive in the scene at any moment, making score static will solve all problems: it can be accessed as EnemyHealth.score and will survive to the object, thus incrementing it before dying works fine. Furthermore, the score won't be overlapped by the others because only one enemy is alive in scene:
public static float score = 0f;