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. Dismiss Notice

Is it possible to have an "Object Reference Library" be derived by a static class?

Discussion in 'Scripting' started by Galactic_Muffin, Jan 19, 2016.

  1. Galactic_Muffin

    Galactic_Muffin

    Joined:
    Aug 14, 2013
    Posts:
    67
    So I'm kinda new to the programming side of Unity considering i started out as an artist. There are things that i have learned that are best practices and one of these things is referencing Objects and GameObjects in your scene. Many Unity forum posts say that a direct public reference to Game objects and their components set in the inspector are always better than finding references in Start() or in Update(). but lets say i wanted to have all my references readily available to use throughout my whole scene, is it possible to make a "library" of public object references that is simply just that, a list of references. then use that "library" or inherit from that library with lets say a static GameManager class so that all other classes in the scene can just access that static class and have all the references and global methods at their disposal?

    If this is impossible or not the best way, what is the best and cleanest way to reference GameObjects, Objects and components for the whole scene without having to make a messy web of references between all scripts?

    Thanks for any help on the subject! :3
     
    Last edited: Jan 19, 2016
  2. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    I don't see harm in looking up a few references in Start() or even in Update. Simply cache these values into a local, private variable so that you don't need to look up references more than once. I think this is much better than trying to inherit from a library of all possible references, many of which you don't care about.
     
    Galactic_Muffin likes this.
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    huh? :confused: that might hold for GetComponent in Update because getting the same thing programmatically every frame when it doesn't change is not a great expenditure of processing time; but the work around for that would be to move the GetComponent to the Start/Awake functions...
     
    Galactic_Muffin likes this.
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,735
    They're not always better, though more often than not they are. Right tool for the right job. Direct references are often the right tool; sometimes you do need the script to do a little work to find the reference.