- Home /
Int value only changes after I stop playing
I made buttons that when I press them. it lowers the hp of the enemy in the scene, however when I press them nothing happens until I press the play button again to stop playing. After I do this it changes the int value and dosen't reset it to the default of 5. I put 5 buttons in the scene and clicked them all and nothing happened, when I pressed play again to end it and then hit play again it loaded the lose scene. Here is the code in question:
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour
{
public int ehp = 5;
void Update() {
if (ehp <= 0) {
Application.LoadLevel("Lose Screen");
}
}
}
`
and this:
`using UnityEngine;
using System.Collections;
public class ButtonInteraction : MonoBehaviour
{
public EnemyHealth _enemyHealth;
public void DamageButton(int damage)
{
_enemyHealth.ehp -= damage;
}
}
The first is the script on the enemy and the second is the script on the button. Can someone help me with this?
First off, don't use an Update to check whether you are meeting the health criteria. Check in your DamageButton() method:
_enemyHealth.ehp -= damage;
if (_enemyHealth.ehp <= 0) {
Application.LoadLevel("Lose Screen");
}
As for the problem, in the Inspector, have you added the function in the OnClick() field?
Answer by YoungDeveloper · Apr 11, 2015 at 02:22 AM
Update() is called every frame, use it only for things which must be updated.
In your case simple check will do. I made the revision for you.
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour{
public int health = 5;
public void remove(int value){
health -= value;
if(health <= 0){
health = 0;
Application.LoadLevel("Lose Screen");
}
}
}
using UnityEngine;
using System.Collections;
public class ButtonInteraction : MonoBehaviour{
public EnemyHealth _enemyHealth;
public void DamageButton(int damage){
_enemyHealth.remove(damage);
}
}
Ok now I have a new problem. The health still stays at 0 after I end like it was before. I need to have everything for the button to be on a prefab because I instantiate it into the scene, so I can't apply the actual enemy in the scene to the button health thing, I have to apply the enemy prefab to the button which I think is what is causing this problem. Is there a way I can apply the enemy in the scene and not its prefab to the prefab of the button or at the very least check on the enemy in the scene's health in the script or something like that?
Sounds like "prefabs and enemies" is a completely separate question (which should be a new question) and has nothing to do with this.
yeah I thought so. I will post a new question about this.
Your answer
Follow this Question
Related Questions
Enemy atributes script 1 Answer
Enemy Health GUI Issues 0 Answers
Distribute terrain in zones 3 Answers