- Home /
I am trying to access a variable from another script.
I am trying to make it so that if the player gets to close to an enemy they lose 20 health. But it only gets to the first debug.Log. I have probably made a very stupid mistake.
Here are my two scripts.
public class Enemy : MonoBehaviour {
public GameObject Player;
private Playerhealth access;
public int player;
void Start() {
access = Player.GetComponent<Playerhealth>();
player = access.playerHealth;
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Player") {
player -= 20;
Debug.Log("hit");
}
}
}
public class Playerhealth : MonoBehaviour {
public int playerHealth = 100;
void Dead() {
if (playerHealth == 0) {
Destroy(this.gameObject);
Debug.Log("you Died");
}
}
}
Answer by aditya · Oct 08, 2016 at 04:53 AM
in your Enemy class you are just deducting the value of player integer and not the playerHealth integer of your PlayerHealth class ... change your Enemy class to look like this
public GameObject Player;
private Playerhealth access;
void Start() {
access = Player.GetComponent<Playerhealth>();
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Player") {
access.playerHealth -= 20;
Debug.Log("hit");
}
}
Your answer
Follow this Question
Related Questions
(C# and Java)Unable to give the Damage from enemy bullet script to Player Health. 3 Answers
Error: CS0246 Can't access Player Health Script 1 Answer
Enemy Health Problems 1 Answer
Current health may never exceed maximum health 2 Answers
Script Wont Take away health from my player when hit by enemy bullet. 0 Answers