Jump to content
  • Advertisement
  • Remove ads and support GameDev.net for only $3. Learn more: The New GDNet+: No Ads!

  • 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 simco50
      Hello,
      I have regular matrix-based skinning on the GPU working for quite a while now and I stumbled upon an implementation of Dual Quaternion skinning.
      I've had a go at implementing this in a shader and after spending a lot of time on making small changes to the formulas to make it work, I sort of got it working but there seems to be an issue when blending bones.
      I found this pretty old topic on GameDev.net (
      ) which, I think, describes my problem pretty well but I haven't been able to find the problem.
      Like in that post, if the blendweight of a vertex is 1, there is no problem. Once there is blending, I get artifacts
      Just for the sake of just focussing on the shader side of things first, I upload the dual quaternions to GPU which are converted from regular matrices (because I knew they should work).
      Below an image comparison between matrix skinning (left) and dual quaternion skinning (right):

      As you can see, especially on the shoulders, there are some serious issues.
      It might be because of a silly typo however I'm surprised some parts of the mesh look perfectly fine.
      Below some snippets:
      //Blend bones float2x4 BlendBoneTransformsToDualQuaternion(float4 boneIndices, float4 boneWeights) { float2x4 dual = (float2x4)0; float4 dq0 = cSkinDualQuaternions[boneIndices.x][0]; for(int i = 0; i < MAX_BONES_PER_VERTEX; ++i) { if(boneIndices[i] == -1) { break; } if(dot(dq0, cSkinDualQuaternions[boneIndices[i]][0]) < 0) { boneWeights[i] *= -1; } dual += boneWeights[i] * cSkinDualQuaternions[boneIndices[i]]; } return dual / length(dual[0]); } //Used to transform the normal/tangent float3 QuaternionRotateVector(float3 v, float4 quatReal) { return v + 2.0f * cross(quatReal.xyz, quatReal.w * v + cross(quatReal.xyz, v)); } //Used to transform the position float3 DualQuatTransformPoint(float3 p, float4 quatReal, float4 quatDual) { float3 t = 2 * (quatReal.w * quatDual.xyz - quatDual.w * quatReal.xyz + cross(quatDual.xyz, quatReal.xyz)); return QuaternionRotateVector(p, quatReal) + t; } I've been staring at this for quite a while now so the solution might be obvious however I fail to see it.
      Help would be hugely appreciated  
      Cheers
    • By vourkosa
      Hello everyone, I am starting today a new blog called Mobile Indie Spotlight where I will be interviewing mobile indie developers from around the world in an effort to make their stories heard and share their knowledge and experience with others. In these interviews we will be discussing around product and game design, gamification techniques, a/b testing, monetization strategies, localization, app store optimization, social mechanisms, user acquisition and other useful techniques that can help mobile app publishers design and ship better mobile apps on different app stores.
      Below you can find the first interview with Jacky Chou and his app Pluck it! Any feedback or suggestions are more than welcome!
      https://medium.com/@vourkosa/mobile-indie-spotlight-episode-1-pluck-it-a50faa281033
       
    • By Nilmani Gautam
      Unity is a cross-platform game engine developed by Unity Technologies, first announced and released in June 2005 at Apple Inc.'s Worldwide Developers Conference as an OS X-exclusive game engine. As of 2018, the engine has been extended to support 27 platforms.
      I have started a video tutorial on A Complete Game Development course using Unity3d on YouTube. It is completely a beginner to advance course so any on can visit and learn to code and design game from beginning.
      Course will be updated daily.
      Visit here for more information.
      https://www.youtube.com/channel/UCJjDIEeBxUT8VxBVnMXHkDQ
       
       

    • By sevenfold1
      I'm looking for a open source PBR rendering engine that I can use.  Basic requirements are Windows (C/C++) and free to use type license.

      The first two hits I get on Google are:

      Filament
      https://github.com/google/filament/

      LuxCoreRender
      https://luxcorerender.org/

      Does anybody have any experience using any of these, or do you recommend something else that's better?
      Thanks.
      Pluses: Active development, easy to compile, zero dependencies.
  • 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!