C# Extension Method for Object

后端 未结 6 1904
萌比男神i
萌比男神i 2021-02-06 22:22

Is it a good idea to use an extension method on the Object class?

I was wondering if by registering this method if you were incurring a performance penalty as it would b

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 23:01

    This is an old question but I don't see any answers here that try to reuse the existing find function for objects that are active. Here's a succinct extension method with an optional overload for finding inactive objects.

    using System.Linq;
    
    namespace UnityEngine {
    
    public static class GameObjectExtensionMethods {
    
        public static GameObject Find(this GameObject gameObject, string name, 
            bool inactive = false) {
    
           if (inactive)
              return Resources.FindObjectsOfTypeAll().Where(
                 a => a.name == name).FirstOrDefault();
           else
               return GameObject.Find(name);
        }
      }
    }
    

    If you use this function within the Update method you might consider changing the LINQ statement with an array for loop traversal to eliminate garbage generation.

提交回复
热议问题