- Home /
Why is OnTriggerStay is not working?
Hey everybody!
So I am having a problem with OnTriggerStay. I have two game objects. The first game object is my player. He has a Trigger Capsule Collider component around his entire body and a Character Controller component. The second game object is my enemy and has a RigidBody and a Trigger Capsule Collider. I am trying to get the enemy to harm the player when the player enters the enemy's trigger. For the most part, OnTriggerStay works and my enemy does harm to the player, but every now and then, the enemy does zero harm to the player even when the player is inside the enemy's trigger. Here is the code:
void OnTriggerStay ( Collider other) {
GameObject hitObject = other.transform.gameObject;
PlayerHealth target = hitObject.GetComponent<PlayerHealth> ();
if (target == null) {
return;
}
target.TakeDamage (10);
}
The problem is that sometimes the 'target' variable is set to null because the enemy cannot access the player's 'PlayerHealth' script even though he is inside the trigger. I'm just really confused as to why it works only most of the time. Do you have any suggestions?
Answer by Vollmondum · Jul 05, 2017 at 08:19 AM
Replace OnTriggerStay to OnTriggerEnter and Exit. Say OnEnter, your Players script enabled some bool "takeDamage" that invokesRepeating of taking constant damage. TriggerExit sets bool to false. You'll save some on performance.
That worked! I'm not entirely sure why it worked, but I haven't encountered any problems yet. Thank you!
TriggerStay is basically alternative Update function. You don't want that for over 1-2 seconds
Your answer
