Some times you need to make sure a component has been set on a game object and if it does not exist add it.

        /// <summary>
        /// Tries to get a component and if it does not exist adds the component and returns a reference to it. 
        /// </summary>
        /// <remarks>
        /// <example>
        /// Usage example:
        /// <code>
        /// var boxCollider = transform.GetOrAddComponent<BoxCollider>();
        /// </code>
        /// </example>
        /// </remarks>
        public static T GetOrAddComponent<T>(this Component child) where T : Component
        {
            var result = child.GetComponent<T>();
            if (result == null)
            {
                result = child.gameObject.AddComponent<T>();
            }

            return result;
        }

Add comment



biuquote
  • Comment
  • Preview
Loading






Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume