- Home /
Health Script Collision Help!
hi i am trying to make a health script with gui text. Everything works except i want to be able to decrease the players health when they get within a certain range of a certain game object. Ill list the code below. All help would be greatly apprecieated. Thanks! ill list the code here that i have so far
var curHealth : int = 100;
var maxHealth : int = 100;
var curHealthText : GUIText;
var maxHealthText : GUIText;
var range : int = 5;
var player : GameObject;
function Update () {
if(player < range)// this is where im having trouble
curHealth - 10;
if(curHealth < 10) { // loads a death screen when the players health is less than 10
Application.LoadLevel(2); }
if(curHealth > maxHealth) { // if the current health is greater than the max health it
will stay at 100
curHealth = maxHealth; } } }
Answer by Olith · Jun 22, 2013 at 04:53 AM
Hmm... The way I would go about making an object do damage to the player as he or she comes within its attack range, would be to basically treat the object as an enemy. More or less give this enemy GameObject, it own basic attack script that constantly tries to hit the player whether in range or not.
During each attack attempt, the enemy object’s script calculates the vector3 distance between the object and the player and returns a float. If the player is within the designated range (vector3.distance float =< defined max attack range) the attack succeeds. When the attack succeeds the object’s script sends an update to the player’s health script located on the player character GameObject to recalculate the player current health.
Now it is probably a good idea to also add a basic attack cooldown between the enemy object’s attacks. Otherwise the player could die extremely fast. Depending on how much damage the enemy object does each hit. As well as how many update cycles happen per second, while the player is within range.
Now that my logic is out of the way, I go ahead and give you a code example to mess around with. I did it in C# (personal preference), so you may have to personally translate it, if you want it in javascript. I have commented pretty much everything and the code should be easy enough to understand, whether you normally use C# or Javascript.
Step 1: Make a new scene and name it whatever you want.
Step 2: Fill the scene with some form of ground for the player character to walk on and give it a light source.
Step 3: Now create a player GameObject that can move around. First Person Controller will work fine.
Step 4: Create a cube to be your enemy GameObject. Name it whatever you want. Make sure you space it a little be away from your player object. We do not want the player within its attack range at the start of runtime.
Step 5: Create a new C# script and name it “PlayerHealth” without quotes. Make sure you spell as you see it and without typos. C# is very picky about class name matching the file name.
Step 6: Open PlayerHealth.cs in MonoDevelop, copy and paste the following code in it and save.
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int currentHealth = 100; // Players's current health
void Update () {
AddjustCurrentHealth(0); // checks if currentHealth needs adjusting.
}
public void AddjustCurrentHealth (int adjustHP) {
// Adds a given adjustment to the players's current health
currentHealth += adjustHP;
if (currentHealth < 100){
// Creates a log in unity each time the player takes damage
Debug.Log("Player took " + adjustHP +
" damage points. current HP:" + currentHealth);
// Reset health back to 100, so we can log more attacks
currentHealth = 100;
}
}
}
Step 7: Drag the PlayerHealth C# script onto your player character GameObject making it a component.
Step 8: Create a new C# script and name it “EnemyAttack” without quotes. Make sure you spell as you see it and without typos.
Step 9: Open EnemyAttack.cs in MonoDevelop, copy and paste the following code in it and save.
using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour {
// Set player GameObject as the target in the inspector
public GameObject target;
// Holds the enemy object's active attack delay timer
public float attackDelay;
// Holds the enemy object's attack cooldown
public float coolDown;
// Holds the enemy object's attack range
public float attackRange;
// Holds how much damage the enemy object does per atk
public int attackPower;
void Start () {
attackDelay = 0;
coolDown = 2.0f;
attackRange = 3.5f;
// Use a negative number for attackPower
// The current health updated logic is
// (currentHealth += attackpower)
attackPower = -10;
}
void Update () {
// Checks if the enemy object can attack.
AttackDelayTimer();
}
private void AttackDelayTimer(){
if (attackDelay > 0){
// If attackDelay is greater then 0,
// Reduce attackDelay by 1 second per cycle
attackDelay -= Time.deltaTime;
}
if (attackDelay < 0){
// Prevents attackDelay from ever becoming less than zero
attackDelay = 0;
}
if (attackDelay == 0) {
// Sets attackDelay to = coolDown to force delay between atk
attackDelay = coolDown;
// Allow an attack
Attack(); // handles object's attacking.
}
}
private void Attack() {
// Calculates the distance between the enemy object and it's target
float distanceFromTarget = Vector3.Distance
(target.transform.position, transform.position);
if(distanceFromTarget < attackRange) {
// Checks if the target is within attack range
// Loads the target's PlayerHealth script
PlayerHealth playerHP = (PlayerHealth)
target.GetComponent("PlayerHealth");
// Sends an attack update to the PlayerHealth script
// to reflect the attack
playerHP.AddjustCurrentHealth(attackPower);
}
}
}
Step 10: Drag the EnemyAttack C# script onto your enemy GameObject making it a component.
Step 11: Click on the enemy GameObject so you can see it’s inspector. Under the EnemyAttack script component you should see a public variable that is called target and a place for a GameObject next to it. Drag your player object onto it. Thereby making your player object the target of enemy object’s script.
Step 12: Make sure everything is saved and there are no errors.
Step 13: Make sure your console is open so you can see it during runtime and hit play. Move your character next to the enemy object. You should start getting “Player took -10 damage points. current HP:90” log comments in your debug console. Every few seconds, while your player object is within the attack range. If you get the comments that means everything is working as intended.
Step 14: Read the comments and mess around with the variables/code in EnemyAttack.cs and PlayerHealth to figure how you can implement the example’s logic into your own project.
Have fun and hope this helps. - Olith
Your answer
![](https://koobas.hobune.stream/wayback/20220613104642im_/https://answers.unity.com/themes/thub/images/avi.jpg)