Created
May 20, 2011 22:37
-
-
Save ZeroStride/983947 to your computer and use it in GitHub Desktop.
Fast access to information on a Unity GameObject without having to call GetComponent.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| public class FastLookup : MonoBehaviour | |
| { | |
| [SerializeField] | |
| public static int LookupListSize = 1597;//547; //!< Size of static data arrays. Prime numbers are best, in theory. | |
| public const uint FlagAllocated = 1 << 0; //!< This index has been reserved for use. | |
| public uint Idx; //!< Per-instance index into the static data arrays. | |
| //! Convert an instance id to a FastLookup Index. | |
| //! | |
| //! @param instanceId Unity Object instance id, obtained via Object.GetInstanceID() | |
| //! | |
| //! @return A unique index into the FastLookup static data arrays. | |
| public static uint InstanceIdToIndex(int instanceId) | |
| { | |
| return (uint)instanceId % (uint)Flags.Length; | |
| } | |
| #region Data Arrays | |
| public static uint[] Flags; | |
| public static Vector3[] LastPosition; | |
| public static Vector3[] Position; | |
| #endregion | |
| #region MonoBehavior Stuff | |
| void OnEnable() | |
| { | |
| if(Flags == null) | |
| { | |
| Flags = new uint[LookupListSize]; | |
| LastPosition = new Vector3[LookupListSize]; | |
| Position = new Vector3[LookupListSize]; | |
| } | |
| Idx = InstanceIdToIndex(gameObject.GetInstanceID()); | |
| // If we're debugging, put in some extra checks | |
| #if UNITY_EDITOR | |
| if((Flags[Idx] & FlagAllocated) == FlagAllocated) | |
| { | |
| Debug.Log("InstanceId collision detected! Consider increasing lookup list size."); | |
| Debug.Break(); | |
| } | |
| #endif | |
| Flags[Idx] = FlagAllocated; | |
| } | |
| void OnDisable() | |
| { | |
| Flags[Idx] = 0; | |
| } | |
| #endregion | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment