- Home /
How to speed up a trigger enter function?
I am making a FPS game and the trigger rate doesn't run quick enough to hit all objects, here is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CustomNormalBullet : MonoBehaviour { public float Damage = 25f; public float lifetime = 3f; public float afterImpactLife = 0.5f;
private void Awake()
{
StartCoroutine(DelayedDestroy());
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("hit " + other.name + "!");
Target target = other.GetComponent<Target>();
if (target != null) target.TakeDamage(Damage);
}
IEnumerator ImpactDelayDestroy()
{
yield return new WaitForSeconds(afterImpactLife);
Destroy(gameObject);
}
IEnumerator DelayedDestroy()
{
yield return new WaitForSeconds(lifetime);
Destroy(gameObject);
}
} I have a rigidbody system to shoot the bullet at "200 force" in rigidbody terms, I have calculated a 70 percent error rate, is there any way to increase the frequency of the trigger scanning?
there are 2 ways, changing the rigidbody settings to continues dinamic or increasing the fixed time step (not recommended, will recalculate ALL forces more frequently, not just triggers)
Answer by Captain_Pineapple · Feb 16 at 12:07 PM
Hey,
you can either follow @xxmariofer s advice which would probably work in most cases.
BUT
it doesn't have to. If you have small fast moving objects in Unity then the actual impact calculations can be weird to say the least.
The most reliable way to get a proper small projectile would be a raycast approach. Now i don't mean hitscan but basically a custom projectile with a body that moves to a certain point and does a raycast to its movement direction each frame. If something is hit, hit it. If nothign is hit, move there and wait for the next frame. You'd have to apply gravity artifically but this system works quite good for me in general and solved all my issues that i formally had with missing/inaccurate hits.
Thank you so much my projectile gun now works without problems!