Hello,
I have script attached to Player and another script attached to multiple Enemies
Anyway, I’m not sure how to access variables from Enemy script so Player can take damage, get experience and etc.
Writing public Enemy myEnemy;
doesn’t work in Player script and I really don’t know how to fix it.
EnemyScript
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour{
public int Health;
public int Damage;
public int Experience;
}
Player Script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//------------------------------------------------------------------------------------
public class Player{
//Player attributes.
private int Health;
private int Mana;
private int ReqExp;
private int CurrExp;
private int Level;
private int Damage;
//Set values of player attributes.
public void SetValues(int HP, int MP, int R_EXP, int C_EXP, int LVL, int DMG){
Health = HP;
Mana = MP;
ReqExp = R_EXP;
CurrExp = C_EXP;
Level = LVL;
Damage = DMG;
}
//Player take damage from enemy and lose DMG of health points.
public void GetDamage(int DMG){
if (Health > 0) {
Health -= DMG;
}
if(Health <= 0;){
GameObject.Destroy (GameObject.FindGameObjectWithTag ("Player"));
Debug.Log ("You're dead!");
}
}
public int GetHealth(){
return Health;
}
}
//------------------------------------------------------------------------------------
public class PlayerScript : MonoBehaviour {
public Player myPlayer;
public Enemy myEnemy; // <-- I'm doing it wrong, yes?
public float distance; //Distance between player and enemy.
public Text myHealthText; //Health text.
void Start(){
//(Health, Mana, ReqExp, CurrExp, Lvl, Damage).
myPlayer.SetValues (100, 100, 130, 0, 1, 10);
}
void Update () {
distance = Vector3.Distance(gameObject.transform.position,
GameObject.FindGameObjectWithTag("Enemy").transform.position);
if (distance <= 3) {
myPlayer.GetDamage (myEnemyScript.Damage); //Get damaged by enemy.
StartCoroutine (WaitAfterHit ()); //Wait few seconds after hit.
}
myHealthText.text = "Health " + myPlayer.GetHealth().ToString(); //Show player health.
}
IEnumerator WaitAfterHit(){
yield return new WaitForSeconds (5);
}
}
}