Fast and powerful reflection utilities for Unity.
| Documentation | Benchmarks |
|---|
Hopefully, fast enough!
| Field access | Elapsed time (ticks/100,000 accesses) | Ratio vs. compiled |
|---|---|---|
| Compiled | 37,515 | 1x |
| Getter | 43,204 | 1.152x |
| Reflection | 317,665 | 8.468x |
This works by building a Getter or Setter object. These objects can be used to read or write to a specific property of a specific type.
- Call the
Buildmethod to construct one, passing in a root type (SpriteRenderer, in this case) and a property name ("color".) - Pass in the type of the named property ("color") as a generic type parameter (
Color.) - Use the
GetValueorSetValuemethod on an object of the root type.
public SpriteRenderer root;
private Getter<Color> _getter;
private Setter<Color> _setter;
void Awake()
{
_getter = Getter.Build<Color>(typeof(SpriteRenderer), "color");
_setter = Setter.Build<Color>(typeof(SpriteRenderer), "color");
}
void Start()
{
var retrievedColor = _getter.GetValue(root);
_setter.SetValue(root, Color.yellow);
}Getter and Setter are simply wrappers around code that compiled a LINQ Expression via the C# expression tree API.
More benchmarks can be found here.
This repository includes a couple common applications for which Getters and Setters are useful.
Dynamically reference a field, property, or parameter-less method on any Object. Great for consolidating scripts whose only difference is a type!
[SerializeField] private PropertyReference<Color> colorProperty;
private void Start()
{
colorProperty.Initialize();
GetComponent<SpriteRenderer>().color = colorProperty.Value;
} This is similar to building a Getter, but:
- It references a specific property on a specific object, not any object of the root type.
- It has a really nice custom property drawer.
Easy, dynamic custom Inspector. Only uses PropertyDrawers for total compatibility with existing custom editors.
public bool shouldUseRaycast;
[ShowIf("shouldUseRaycast")] public float raycastLength;
[HideIf("shouldUseRaycast")] public float detectionRadius;
public bool useCustomTitle;
[DisableIf("useCustomTitle")] public string defaultTitle;
[EnableIf("useCustomTitle")] public string overrideTitle;It's easy!
- Open the Unity Editor. On the top ribbon, click Window > Package Manager.
- Click the + button in the upper left corner, and click "Add package from git url..."
- Enter "https://github.com/bgsulz/Reflectors-for-Unity.git"
- Enjoy!
- Click the big green "Code" button and click Download ZIP.
- Extract the contents of the .zip into your Unity project's Assets folder.
- Enjoy!
