- Home /
Best approach for a distance based destroyer
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?
Answer by Befall · May 16, 2012 at 08:11 PM
First off, I'm unfamiliar with the Object Pool Manager use, but for each one, why not just use Destroy(gameObject)? Also, try testing out a single script, possibly a Coins script or something, iterating through the coins each frame, instead of each coin having a script itself that is called every frame.
No matter what, you'll need to check every frame for each coin, it just may be easier to do something like this:
List<GameObject> toDestroy = new List<GameObject>();
foreach (GameObject coin in coins)
{
if (Vector3.Distance(playerRef.transform.position, coin.transform.position) > maxDistance)
toDestroy.Add(coin);
}
foreach (GameObject destroyCoin in toDestroy)
{
coins.Remove(destroyCoin);
Destroy(destroyCoin.gameObject);
}
The reason for the second list thingy is because you can't be iterating through a list and adjust its members. This is just a rough guess and may not suite you, but it would keep all your necessary code in one spot for coin removal.
También, si nunca has usado un List antes, tienes que incluir "using System.Collections.Generic" al principio de su code.
Your answer
Follow this Question
Related Questions
Instantiate vs caching GameObject in scene 3 Answers
Understanding the profiler 1 Answer
Profiler Windows - What is "Others" 1 Answer
What could be causing my super low performance on my Android tablet? 3 Answers
Huge "other" in Gpu Profile ! 4 Answers