- Home /
Kill the Player?
I made this script, but I cant seem to figure out how to make him die. I would like the scene to reset when his health hits 0. Here is the script:
using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour {
public GameObject target;
public float attackTimer;
public float coolDown;
// Use this for initialization
void Start () {
attackTimer = 0;
coolDown = 2.0f;
}
// Update is called once per frame
void Update () {
if(attackTimer > 0)
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
attackTimer = 0;
if(attackTimer == 0){
Attack();
attackTimer = coolDown;
}
}
private void Attack(){
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
if(distance < 2.5f) {
if(direction > 0) {
PlayerHealth eh = (PlayerHealth)target.GetComponent("PlayerHealth");
eh.AddjustCurrentHealth(-10);
}
}
}
}
You forgor to mark your code as code, now UnityAnswers turned it into FUBAR and i won't fix that. Please copy it again from your original source, edit your question and replace the code but don't forget this time to highlight the code and press the "101 010" button.
Answer by OperationDogBird · Sep 01, 2012 at 07:18 AM
At the very end of your Attack function you should check if the players current health -10 <= 0 , if so run whatever method you have for that. It most likely is also on the players script, so just call the function if that conditional is met.
if(direction > 0) {
PlayerHealth eh = (PlayerHealth)target.GetComponent("PlayerHealth");
if(eh.health-10 <= 0) //eh.Killed();
else eh.AddjustCurrentHealth(-10);
}
Depending on if you display the health after you die, you may want to either subtract the health first and then run the conditional check or just subtract the 10 from the Killed() function itself. Either or, but not both ;)
Your answer
Follow this Question
Related Questions
How can I load a scene when the enemy hits the player? 5 Answers
Enemy targeting player in different scene 1 Answer
enemy targeting player in different scene 1 Answer
When Near Object, Change Scene 0 Answers
Reset a timer? 0 Answers