Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

GameObjects with identical names

Discussion in 'Editor & General Support' started by skinner92, Sep 23, 2016.

  1. skinner92

    skinner92

    Joined:
    Feb 23, 2014
    Posts:
    112
    Hello there.

    To my surprise, Unity allows me to create multiple GameObjects with identical names. Isn't this a clear drawback? For example, what if you are using the GameObject.Find() method, but you accidentally named two or more GO's the same? This is not a problem for small games, but I still would like Unity to warn me (at least) when I have two GO's with the same name. Is this possible? Thanks!
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    In big games, it's very common to have objects with the same name.

    Consider this: you have 20 enemies each firing machine guns, so there are 100s of bullets in the scene. It would be a bit silly to generate a unique name for each bullet.

    GameObject.Find() is a convenience method for beginners, but it's very inefficient because you're basically looping through every object and checking if the name is what you're looking for. It's far better to use public fields and serialized fields to set up references to other objects so you don't need to call a "Find" method.

    The following manual page shows you that you can make public variables in code and fill out the values in the unity inspector. You can do the same thing with a public GameObject or other script you've made, just click-and-drag the other object from the Hierarchy into the empty field in the inspector.
    https://docs.unity3d.com/Manual/VariablesAndTheInspector.html
     
    skinner92 and ProtoTerminator like this.
  3. skinner92

    skinner92

    Joined:
    Feb 23, 2014
    Posts:
    112
    Thank you Gambit-MSplitz for your useful answer. I will avoid the Find method at all costs now!
     
  4. ProtoTerminator

    ProtoTerminator

    Joined:
    Nov 19, 2013
    Posts:
    566
    The Find method can be useful in Start or Awake functions to set stuff up (also FindObjectsWithTag is very useful and much more efficient), but it's not something you want to use continuously, like in Update.
     
    skinner92 likes this.
  5. skinner92

    skinner92

    Joined:
    Feb 23, 2014
    Posts:
    112
    I'll have that into account ProtoTerminator, thank you ;)