So I’m trying to create an enemy that on contact decreases Player health by 10 Player Health script
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
// Use this for initialization
int Health = 100;
public void Start () {
}
// Update is called once per frame
void Update () {
if (Health == 0)
{
Application.LoadLevel("GameOver");
}
}
void OnGUI () {
}
public void ChangeHealth(int howMuch){
this.Health += howMuch;
}
}
Enemy Script
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
// Use this for initialization
public void OnCollisionEnter(Collision collision)
{
PlayerHealth playerHealth = GetComponent();
if (collision.gameObject.tag == "Player")
{
if(playerHealth == null) return; // Get out.
while(playerHealth.ChangeHealth = 100)
{
playerHealth.ChangeHealth(-10);
}
}
}
// Update is called once per frame
void Update () {
}
}
I’m getting Error CS0103: The name Health does not exist in the current context Help?
- playerHealth.Health -= 10;
Health is a member if PlayerHealth component, not of enemy.
- This collision logic looks like it belongs to the player - yet it is defined in the enemy class.
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
private int Health = 100;
public void Start () {
// You can't create the health variable here or it'll go away as soon as Start exits.
}
// Update is called once per frame
void Update () {
}
//Other classes shouldn't be updating the variables of this class - make a method to do this work, like this:
public void ChangeHealth(int howMuch){
this.Health += howMuch;
}
}
Enemy…
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public void OnCollisionEnter(Collision collision)
{
This should be fine, but you should also check for null
PlayerHealth playerHealth = collision.GetComponent<PlayerHealth>();
if(playerHealth == null) return; // Get out.
// You should be checking this item, not the collided item to be sure it's enemy since the collision will be a player (I think)
if (this.gameObject.tag == "Enemy")
{
playerHealth.ChangeHealth(-10);
}
}
// Update is called once per frame
void Update () {
}
}