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

Access object directly during runtime

Discussion in 'Editor & General Support' started by crowmagnon, Apr 9, 2015.

  1. crowmagnon

    crowmagnon

    Joined:
    Mar 2, 2011
    Posts:
    36
    Hi, is there any way to access a newly created object directly during runtime? Without having to use GameObject.Find to troll through every active object? Or if I want to make a reference between a new object and another object that is currently inactive? Here is my case:

    I have a game with three characters you can cycle among at any time. The currently chosen character is active while the other two are inactive. There are multiple scenes in the game, one for each area explored, and these three character objects are the only objects that persist through all of the different scenes.

    Each scene has a separate camera object that is instantiated upon the loading of the scene, which must have a reference to each character. I would like to avoid using the .Find function to find these character objects by name, because of how slow I've heard it is. But on top of that, two of the character objects are always inactive, which makes .Find not even an option.

    Any ideas on how I can dynamically make these connections?
     
  2. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    Put them into a static variable somewhere?
     
  3. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    Lazy answer. :p

    Since you're the one making the object just assign it to a public variable when you create it. You can do that, or add it to a list, which is what I like to do. I basically use lists as my own tagging system. If I need an object categorized I make a list and add it to that list. Then if I have to find an object I'm only looping through a small... Ish... Number of objects. Make the lists static and you can get them from anywhere during run time. The lists are nice because it's not always reasonable to have a static variable for every object, especially when the number of objects are unknown.
     
  4. crowmagnon

    crowmagnon

    Joined:
    Mar 2, 2011
    Posts:
    36
    Oooo, I like that idea, I think that's just what I need, thanks!