- Home /
Calling a variable from one script to another
I have two scripts, one is a health script, the other is a damage script. At the moment, the damage script just destroys the enemy as soon as the weapon touches it. But how do I make it deduct a specific amount of health when it hits the enemy?
This is the health script
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour
{
public int maxHealth;
public int MaxHealth
{
get {return maxHealth;}
}
public int currentHealth;
public int CurrentHealth
{
get {return currentHealth;}
}
public void ModifyHealth (int modifyAmount)
{
currentHealth += modifyAmount;
if (currentHealth <= 0)
{
currentHealth = 0;
}
else if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
}
public void SetMaxHealth (int setAmount)
{
maxHealth += setAmount;
}
void Start ()
{
SetMaxHealth (100);
ModifyHealth (100);
}
}
This is what I have of my damage script so far:
using UnityEngine;
using System.Collections;
public class Damage : MonoBehaviour
{
public void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
Thanks, Brendan
Comment
Best Answer
Answer by ncallaway · Jan 06, 2014 at 02:29 AM
In the damage script, you can get the Health component from the other object. Once you've got that, you can access public variables, properties, and methods on that component.
using UnityEngine;
using System.Collections;
public class Damage : MonoBehaviour
{
public void OnTriggerEnter(Collider other)
{
Health enemyHealth = other.GetComponent<Health>();
if (enemyHealth == null)
{
// you've collided with an object that doesn't have a health component.
// you can handle this however you want...
}
else
{
enemyHealth.ModifyHealth(-10); // or whatever damage value you want...
}
}
// I've omitted the rest of the Damage script, as it's not relevant
}
Your answer
Follow this Question
Related Questions
Enemies sharing health 2 Answers
Help w/variables 0 Answers
Health Code, Damage and Healing 0 Answers
how to make enemy damage player? 1 Answer
Problem with 2 scripts communicating 0 Answers