Search Unity

New tag or GetComponent

Discussion in 'Scripting' started by dbordzo, Feb 14, 2016.

  1. dbordzo

    dbordzo

    Joined:
    Aug 14, 2015
    Posts:
    34
    Hello,
    I wanna ask you which is better option I mean faster:

    I have 3 types of bombs. When player will be on trriger then he will get one type of bomb.
    And here is my question, which is better option,
    If I will add tags to obejct and copare this onTrigerEnter, or make script and I will have less tags, but I will had to getcomponent during OnTrigger.

    Which option is better (faster) you think?
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    The tag one, imagine:
    You have a two tags (for this example "trigger01" and "trigger02")
    switch (collider.gameObject.tag) {
    case "trigger01":
    do stuff
    break
    default
    etc etc...
    }

    because gameObject is the parent of collider, therefore there can be only one gameObject and tag is a variable of gameObject, this proccess is faster

    There can be infinite amount of components inside a gameObject, and if you want to find one, the code needs to iterate over every one of them.

    It really doesn't matter, which one you use until there are 1000 components on the gameObject or 1000 gameObjects doing this in the scene
     
    dbordzo likes this.
  3. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Also naming the Object could be an option too, because then you don't need to create 10 tags for every single one
     
    dbordzo likes this.
  4. dbordzo

    dbordzo

    Joined:
    Aug 14, 2015
    Posts:
    34
    Thank you very much :)
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Both tags and names are string based. Be careful about relying on strings when coding. They are error prone.

    You could actually switch this up. Move the code onto the actual bomb, instead of the player. Then add an appropriate interface. Now you can call the bomb code once, regardless of how many bomb types there are.
     
    dbordzo and gorbit99 like this.