How to make HP decrease on a Collision with specific amount

Hello everyone!

I’m making my character decrease Hp on a certain collision that is tagged as Harmful.

But I’m having trouble decreasing the Hp with specific amount.

See I’m like trying to make my character decrease a certain amount of hp given from the Damage of the collided object.

So I made 2 separate scripts one that has all of my characters functions and Hp and what not and one that has a script named Damage.

If my Character collides with the Object my Character minuses Hp from the given damage from the script. Such as 25 points, 200 points and so on.

I tried doing this with my script but for some reason my DamagePoints Var is Highlighted as red.

	void OnTriggerStay2D (Collider2D coll) {
		if (coll.gameObject.tag == "Harmful") {
			coll.gameObject = coll.GetComponents(typeof(Damage).DamagePoints - HP);



				}
		}

Here’s my Damage Script. Although it’s pretty simple.

Inside my public float DamagePoints I have it set as 25.

using UnityEngine;
using System.Collections;

public class Damage : MonoBehaviour {

	public float DamagePoints;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

I do something similar in one of my projects…

public int livesValue = 1; // Amount of lives to be deducted/added to the player
	
	void OnTriggerEnter(Collider collider)
	{ 
		if(collider.gameObject.name == "Player")
		{
			    LivesManager.lives -= livesValue; // Decrease Player Lives total
		}

LivesManager refers to the name of the other script. lives is the ‘static’ variable on the other script that holds my lives number (in your case the amount of health)

On this script I simple make another variable (livesValue) give it a value, this can be done private or public.

Then on the collision/trigger I simply reference my other script and variable and tell it to deduct the value I’ve set in this script.

Something like this would work again in your case.

Also unity have a nice tutorial video on accessing data/variables held on other scripts

http://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent

:slight_smile:

I think the fastest way of fixing this is adding parentheses more correctly and using “GetComponent” instead of “GetComponents”:

coll.GetComponent(typeof(Damage)).DamagePoints - HP;