I am creating a game which the player collect coins and keeps going up. I need this coins to disappear when the user is too far.
What I am doing right now is adding a component to the coins with the following:
public class PlayerDistanceBasedDestroyer : MonoBehaviour
{
private Transform target;
void Awake()
{
this.target = GameObject.Find("Player").transform;
}
void LateUpdate ()
{
if ( (this.target.position - this.transform.position).y > PlayerFalling.FALLING_WARNING_DISTANCE )
{
ObjectPoolManager.DestroyPooled( gameObject );
}
}
}
Since the profiler showed that it was called a lot I changed this to the following:
public class PlayerDistanceBasedDestroyer : MonoBehaviour
{
private Transform target;
void Awake()
{
this.target = GameObject.Find("Player").transform;
}
void onEnable()
{
StartCoroutine("DestroyLogic");
}
void onDisable()
{
StopCoroutine("DestroyLogic");
}
private IEnumerator DestroyLogic()
{
while (true)
{
if ( (this.target.position - this.transform.position).y >
PlayerFalling.FALLING_WARNING_DISTANCE )
{
ObjectPoolManager.DestroyPooled( gameObject );
}
yield return new WaitForSeconds(1f);
}
}
}
While testing this second implementation it felt slower (Nothing is said in the profiler).
Do you think there is a better approach?