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

  • Advertisement
  • Popular Now

  • Similar Content

    • By exzizt
      Hey everyone! I just wanted to announce that after eight months of hard work, we're approaching the launch of our second BETA! Everyone who signs up gets to be the first to play.
      Signup here: https://www.playbirdie.com/

    • By midn
      Since I'm not a good 2D artist (learning sloowly with low motivation but that's a different topic) here's what the current art process is:
      Model a thing in Blender. Render it in a low resolution. Using ImageMagick apply a color palette. The palette is I think the SNES palette that I took from Wikipedia and cropped a little bit.
      There's a problem though, below is a screenshot of the game. Excuse the size :P.
      It's extremely dark, I can't say if it can be passed off as just a "style" but it's even a bit hard on my eyes. And see the background, the black with green spots? That's supposed to be tall grass, but the palette reduces detail until it just looks like overly peppered lettuce.
      The white rectangles will be ladder sprites, it's unfinished at the moment.

    • By _Flame_
      Hello.
      I'm wondering how to implement good lighting for a billboard.
      Currently i have only one normal that points to a viewer's direction. It's ok for a flashlight  but bad for point light.
      I have heard about normal map atlas but I don't know how to create it.
      Any suggestions?
    • By ThomasG_art
      A complete scene and prefabs created in unity. allow you to get you started rapidly.
      Mountains, ruins and cave areas are all included:

      http://u3d.as/1ypw 

      The cliffs/rocks and ruins feature a trilanar shader, you can customize the colors/textures and overlays. The water and vegetation shader are also customisable. 
      The trees/vegetation prefabs are using unity's terrain system and are already set-up for you. The ruins prefabs are modular and fit on a grid. 
      The cloths prefabs are using unity cloth's system and can be adjusted. 
      Particle effects, air particles, clouds, mist , butterflies, etc...

      Trailer:
       




    • By horror_man
      Hello, I'm currently searching for additional talented and passionate members for our team that's creating a small horror game.
      About the game: The game would be a small sci-fi/post-apocalyptic survival horror 3D game with FPS (First person shooter) mechanics and an original setting and story based in a book (which I'm writing) scene, where a group of prisoners are left behind in an abandoned underground facility. It would play similar to Dead Space combined with Penumbra and SCP: Secret Laboratory, with the option of playing solo or multiplayer.
      Engine that'd be used to create the game: Unity
      About me: I'm a music composer with more than 4 years of experience and I'm currently leading the team that's creating this beautiful and horrifying game. I decided that making the book which I'm writing into a game would be really cool, and I got more motivated about doing so some time ago when I got a bunch of expensive Unity assets for a very low price. However, I researched about how to do things right in game development so I reduced the scope of it as much as I could, so that's why this game is really based in a scene of the book and not the entire thing. Also I'm currently learning how to use Unity and learning how to program.
      Our team right now consists of: Me (Game Designer, Creator, Music Composer, Writer), 3 3D Artists, 4 Game Programmers, 1 Sound Effect Designer, 2 Concept Artists, 1 3D Animator.
      Who am I looking for: We are looking for a passionated and talented 3D Environment Artist that's experienced in hard surface models and the creating of closed/underground scenes with a realistic feeling to them. Familiarity with the sci-fi/horror genre is a plus.
      Right now the game is in mid-early development and you can see more information about it and follow our progress in our game jolt page here: https://gamejolt.com/games/devilspunishment/391190 . We expect to finish some sort of prototype in 2 months from now.
      This is a contract rev-share position
      If you are interested in joining, contributing or have questions about the project then let's talk. You can message me in Discord: world_creator#9524
×

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!