- Home /
how do i damage the player on enemy start, Not collision
so i have this basic enemy script that works fine
public class Enemy : MonoBehaviour { public float health; public float damage;
public GameObject deatheffect;
public void Update() {
if (health <= 0)
{
Instantiate(deatheffect,transform.position,transform.rotation);
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider hitInfo)
{
Player player = hitInfo.GetComponent<Player>();
if (player != null)
{
player.health -= damage;
health -= player.attackPower;
}
}
}
but i have a boss that instantiates an object for a health debuff and i dont want the debuff to use collision. i just want the player to lose health on the debuffs Start.
so how do i change the OnTriggerEnter to Start.ive tried this
public class testfox : MonoBehaviour {
public float attackBuff;
public float damage = 4;
public GameObject player;
void Start()
{
player = GameObject.Find("Player");
player.health -= damage;
Destroy(gameObject);
}
},
Comment
Best Answer
Answer by HellsHand · Apr 20, 2021 at 11:14 AM
public float attackBuff;
public float damage = 4;
public PlayerScript player; //Declare variable for the players script
void Start()
{
player = GameObject.Find("Player").GetComponent<PlayerScript>(); //Find the player and get it's script component
player.health -= damage; //Provided health is defined for the player this should do it
Destroy(gameObject);
}
I would suggest to get player reference using built-in player tag. It will be less costly.
player = GameObject.FindObjectWithTag("Player").GetComponent<PlayerScript>();
Answer by lorenzfresh · Apr 20, 2021 at 06:11 PM
// PlayerScript
public class PlayerController : MonoBehaviour{
int health = 100;
public void TaskDamage(int damage) {
health -= damage;
if (health <= 0) {
// GameOver Screen
}
}
}
Enemy Script
public class EnemyAI : MonoBehaviour{
int AttackDamage = 10;
private PlayerController playerScript; // <-- the player script
private void Awake() {
playerScript = GameObject.Find("Player").GetComponent<PlayerController>();
// The PlayerController script must be on the Game Object Player
}
private void Start() {
AttackPlayer(AttackDamage);
}
private void AttackPlayer(int damage){
playerScript.TaskDamage(damage)
}
}