- Home /
how do i use component gathered from ontriggerEnter, outside of that function?
trying to use the "pHealth" variable on a coroutine after the onTriggerEnter event, but pHealth wont work unless inside the trigger event,
private void OnTriggerStay (Collider other)
{
if (other.tag == "Player")
{
PlayerHealth pHealth = other.GetComponent<PlayerHealth>();
// i want to do this VVVV in the coroutine
pHealth.Health -= DamagePoints;
if (isCurrentlyAttacking == true && isCurrentlyDamaging == false)
{
StartCoroutine(DealingDamage());
}
}
}
Answer by SamuelRoos · Jun 05, 2020 at 04:39 AM
The pHealth
variable is defined inside the OnTriggerStay()
function, which means that it is only accessible from inside that function. If you want to access from everywhere inside that script, you need to put it as a global variable.
This is how your bit of code should look like:
//Accessible from everywhere inside this script.
PlayerHealth pHealth;
private void OnTriggerStay (Collider other)
{
if (other.tag == "Player")
{
//Instead of creating a new local variable, you assign the gathered component to the global one.
pHealth = other.GetComponent<PlayerHealth>();
if (isCurrentlyAttacking == true && isCurrentlyDamaging == false)
{
StartCoroutine(DealingDamage());
}
}
}
Your answer
Follow this Question
Related Questions
how do i use component gathered from ontriggerEnter, outside of that function? 2 Answers
Performance issues with GetComponent/gameObject.Find in different functions 1 Answer
Cannot figure out how to find animation in animator by name. 0 Answers
Temporary Buff scripts and timers 2 Answers
A more graceful way to get a list/array of a certain component from all GameObjects of a type? 1 Answer