Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

CompareTag 300 Objects..Is there an efficient way?

Discussion in 'Scripting' started by drndfx, Aug 22, 2020.

  1. drndfx

    drndfx

    Joined:
    Jul 3, 2013
    Posts:
    89
    Hello,

    For object tracking and updating the score, what is more efficient way to do it instead of creating 300 if else statements?

    void OnTriggerEnter(Collider other)
    {
    if (other.gameObject.CompareTag("Ball"))
    {
    Debug.Log ("It's a Ball");
    }
    if (other.gameObject.CompareTag("Car"))
    {
    Debug.Log ("It's a Car");
    }
    if (other.gameObject.CompareTag("Umbrella"))
    {
    Debug.Log ("It's an Umbrella");
    }
    if (other.gameObject.CompareTag("Basket"))
    {
    Debug.Log ("It's a Basket");
    }
    if (other.gameObject.CompareTag("Hat"))
    {
    Debug.Log ("It's a Hat");
    }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    I wouldn't approach it this way... I would put a MonoBehavior on each object that tells how much its' worth, look for that object upon trigger (using GetComponent) and get the points out of there.

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class ScoreValue : MonoBehaviour
    4. {
    5.     public int Points;
    6.     void Reset()
    7.     {
    8.         Points = 100; // default. DO NOT insert number in variable declaration above!
    9.     }
    10. }
    That way you don't need a centralized place to update every time you tweak your game (which you will constantly be forgetting to update), and you don't even need to make code changes when you change what something is worth. Just change the prefab. You can even have different "Hats" worth different values, for instance.
     
    SolarFalcon, PraetorBlue and Yanne065 like this.
  3. drndfx

    drndfx

    Joined:
    Jul 3, 2013
    Posts:
    89
    Thank you. After modifying the code a little bit your suggestion worked.
     
    Kurt-Dekker likes this.