I watched Basic Platformer Game tutorial for Unity where presenter created coin pick-up script that he attached to Coin prefab. I want to know if the pick-up script should be attached to the Player or Coin GameObject.
Let's say we have a game with pick-upable objects. They do nothing more than incrementing the score (or affecting the player in another way) and destroy themselves on collision.
I was wondering that what is the preferred approach to this problem.
I've come up with two approaches:
Approach A
Have one ObjectPickup script on the player game object. This script would do whatever is required depending on the type of collided object.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Coin"))
{
IncrementScore();
Destroy(other.gameObject);
}
else if (other.gameObject.CompareTag("SuperSpeed"))
{
IncreasePlayerSpeed();
Destroy(other.gameObject);
}
}
Approach B
Have CoinPickup script on every coin and SuperSpeedPickup script on every super speed powerup.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
other.gameObject.IncrementScore();
Destroy(gameObject);
}
}
And other script:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
other.gameObject.IncreasePlayerSpeed();
Destroy(gameObject);
}
}
Is Approach A more efficient then Approach B? If so what is the rough number of GameObjects when Approach A becomes preferable?
Or is it always better to work with Approach B as it seems to be cleaner (when we have a number of different pick-upable objects)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…