Jump to content
  • Advertisement
  • 07/04/18 10:10 AM

    Finding Game Objects and Components in Unity with a Simple Pattern

    General and Gameplay Programming

    Ahmed Sabry

    I have some fun here for those who search for game objects and components in the scenes using Unity:

    GameObject.Find("") , FindObjectOfType<> , GetComponent<>

    Or any other searching method. And since searching for objects and components is a high cost operation and annoying for some people. This is a very simple and easy pattern that will make the process easier.
    We start with making a class StaticObjectwhich holds the game object, its name, and a reference to its components that we will need to use.

    And then we create a class AllStaticObjects, which holds a list of the StaticObject to assign in the inspector, and an indexer to search for the desired game object by its name.

    Second step is creating a class StaticObjectComponentwhich holds a component and its name. Then a class AllComponentswhich holds a list of, StaticObjectComponent to assign in the inspector, and an indexer to search for the desired component by its name.

    Of course we don't forget to mark all the classes as 

    [System.Serializable]

    So that they be displayed in the inspector.

    In our manager script, we make a singleton, and a public reference to AllStaticObjects class to assign them from the inspector. Now, if we want to access a game object we can just type it like this:

    GameObject ui =(GameObject)StaticObjectsManager.Instance.AllObjects["UI Canvas"].TheGameObject;
    

    if we want to access a component, we will do:

    var animation = (Animation)StaticObjectsManager.Instance.AllObjects["UI Canvas"].AllComponents["Animation"].Component;
    

    This is the full code.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
     
    [System.Serializable]
    public class AllStaticObjects
    {
        public List<StaticObject> Objects;
     
        public StaticObject this[string name]
        {
            get
            {
                foreach (StaticObject staticObject in Objects)
                {
                    if (staticObject.Name == name)
                    {
                        return (staticObject);
                    }
                }
     
                throw (new MissingReferenceException("The game object with name -" + name + "- is not found"));
            }
        }
    }
     
    [System.Serializable]
    public class StaticObject
    {
        public string Name;
        public GameObject TheGameObject;
        public AllComponents AllComponents;
    }
     
    [System.Serializable]
    public class AllComponents
    {
        public List<StaticObjectComponent> Components;
     
        public StaticObjectComponent this[string name]
        {
            get
            {
                foreach (StaticObjectComponent component in Components)
                {
                    if (component.Name == name)
                    {
                        return (component);
                    }
                }
     
                throw (new MissingReferenceException("The component with name -" + name + "- is not found in the game object " + name));
            }
        }
    }
     
    [System.Serializable]
    public class StaticObjectComponent
    {
        public string Name;
        public Component Component;
    }
     
    public class StaticObjectsManager : MonoBehaviour
    {
        public static StaticObjectsManager Instance;
     
        #region Singleton
        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
                DontDestroyOnLoad(gameObject);
            }
            else
            {
                Destroy(gameObject);
            }
        }
        #endregion
     
        #region Game Objects
        public AllStaticObjects AllObjects;
        #endregion
    }

     



      Report Article


    User Feedback


    There are no comments to display.



    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

  • Advertisement
  • Advertisement
  • Latest Featured Articles

  • Featured Blogs

  • Popular Now

  • Similar Content

    • By Apocaholist
      Hey, I've created an array of lists
      public List<Cube> [] cubes; This array contains a whole map of cubes compressed with RLE (Run-length encoding) to save memory and I'm wondering is it thread safe to resize a single List inside that array while there is only one thread editing that particular list but multiple threads editing other lists inside the same array?
    • By NeoRetro
      Hi -
      I'm a game designer, artist, and game content creator who's been working in the industry on/off for many years.  My work has been primarily on PC and mobile puzzle and action games (Here's an oooold article:  https://www.gamasutra.com/view/feature/130053/breaking_down_breakout_system_and_.php)
       
      I've decided to develop one of my prototypes into a game.  Closest description would be a mashup of Mario Brothers, Mount Your Friends and Cut the Rope.  Single or local multiplayer.  Unity 2D.   
       
      When I began this project in my spare time a few years ago, it was a series of paper and visual prototypes and there were many unknowns.  Since then I've been lucky enough to have pitched the design to a university game incubator in 2017 and have it accepted and developed as a capstone project through Fall/Spring semesters (won best-project award).  This has reduced the unknowns dramatically.  I've also refined and evolved the theme and art style.  Thus my decision to proceed with developing the prototype into a game. 
       
      I've done level scripting in Lua and Objective C, but I don't really have the coding chops to proceed on my own.  Thus I'm looking for an experienced developer with numerous games and prototypes under their belt (bonus points for "2D physics-thing" prototypes and games).  Ideally several years of Unity C# work.  Ideally based in the U.S. since I'm on the east coast. 
       
      This would be a variable amount of revenue share based on contribution (anything from: 4-16 hours per week for a ~12 month duration).  If you're local, there's the possibility of other types of compensation as well (free meals, computer test equipment, etc).  I estimate project completion Sep-Dec 2019. 
       
      I'll provide A TON of specifics for serious inquiries in the form of a brief screenshare walkthrough and short design pitchbook.
      Start would be in early September.
       
      ***Please message me on gamedev.net***
      ***Please include the usual details required to determine qualifications/experience***
      ***Please be over 18***
       
      THANKS FOR READING!
    • By MoreLion
      3D Artists And Unity Programmers For Doom Like Shooter
      Game:ROGUE
      Studio:Rebound Entertainment
      Current Team:3
      Payment:Rev-Share Or Kickstarter
      Programming Requirements:
      - Must Know And Have Experience With Unity And Know C#
      - Must Be Able To Spend 5 To 12 hours a week on the project
      - Must Be Older Than 15
      3D Artist Requirements:
      - Be Able To Model, Animate, Create 3D Monsters And Characters Or Rig (Must Have at least one of these)
      - Must Be Able To Spend 5 To 12 hours a week on the project
      - Must Be Older Than 15
      Project Description:
      You are on the ESL (The Elementary Space Lab). You wake not knowing what has happened, you soon learn that a experimental AI Has gone rogue and created beasts and monsters to kill anything in its path. Now, you know what your mission is.
      If You Are Interested DM Me on discord at thathuman44#4207 or email me at oneriot3@gmail.com
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!