using System; using System.Reflection; using UnityEngine; namespace EnergyBarToolkit { [Serializable] public class ObjectFinder { [Flags] public enum Method { ByPath = 1, ByTag = 2, ByType = 4, ByReference = 8 } public Method chosenMethod = Method.ByType; public string path; public string tag; public GameObject reference; public string typeString; public string assembly; public ObjectFinder(Type type, string defaultPath = "", string defaultTag = "", Method defaultMethod = Method.ByType) { path = defaultPath; tag = defaultTag; chosenMethod = defaultMethod; typeString = type.ToString(); assembly = Assembly.GetExecutingAssembly().FullName; } public T Lookup(UnityEngine.Object parent) where T : Component { switch (chosenMethod) { case Method.ByPath: { GameObject gameObject = GameObject.Find(path); if (gameObject != null) { return GetComponent(gameObject); } Debug.LogError("Cannot find object on path " + path, parent); return (T)null; } case Method.ByTag: { GameObject gameObject2 = GameObject.FindWithTag(tag); if (gameObject2 != null) { return GetComponent(gameObject2); } Debug.LogError("Cannot find object by tag " + tag, parent); return (T)null; } case Method.ByType: { Type type = GetType(); UnityEngine.Object obj = UnityEngine.Object.FindObjectOfType(type); if (obj == null) { Debug.LogError("Cannot find object of type " + type, parent); } return obj as T; } case Method.ByReference: return GetComponent(reference); default: throw new ArgumentOutOfRangeException(); } } private T GetComponent(GameObject go) where T : Component { T component = go.GetComponent(); if (component == null) { Debug.LogError("Cannot find component " + typeString + " on " + go, go); } return component; } private new Type GetType() { return Type.GetType(typeString + ", " + assembly); } } }