- Home /
How do I get the Player's Health Script as Component?
The Player has a Health Script with the Filename PlayerHealthManagement.cs. And every Projectile Prefab which is shot by Enemies, has a DamagingPlayerTrigger.cs Script, which needs a Instance of the Player inside a GameObject Slot to be able to damage him, if he touches it.
Since I can't just Drag the Player Instance inside a Prefab, I need to get it as a Component, but failed.
Can you please help me with the GetComponent Part??
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamagingPlayerTrigger : MonoBehaviour
{
public PlayerHealthManagement _playerHealth;
public int damage = 1;
void Start()
{
PlayerHealthManagement _playerHealth = gameObject.GetComponent<PlayerHealthManagement>();
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.CompareTag ("Plaiyer"))
{
_playerHealth.PlayerHurt(damage);
}
}
}
Answer by JxWolfe · Jan 05, 2019 at 07:58 PM
void OnTriggerEnter2D (Collider2D other)
{
if (other.CompareTag ("Plaiyer"))
{
_playerHealth = other.GetComponent<PlayerHealthManager>();
_playerHealth.PlayerHurt(damage);
}
}
or if you need a reference sooner
void Start()
{
_playerHealth = FindObjectOfType<PlayerHealthManagement>();
}
depends on how soon you need the reference... oh plus you don't want to have the "PlayerHealthManagement _playerHealth = " part, because you just created a new local variable named the same as your class's variable defined above.
Your answer
Follow this Question
Related Questions
Gun Projectile Shooting In Wrong Direction (Javascript) 1 Answer
Please help, bullet drop is wrong at certain angles ? 0 Answers
2D bullet changes direction based on player's world position? 2 Answers
Spawn a bullet of a cannon at right position 1 Answer
Best way to make multiplayer projectiles and enemy shooting player (discussion) ? 0 Answers