Created
November 30, 2018 20:11
-
-
Save aomnes/bcc6e7d9cb2c02c1ecf76f1c48eb48c1 to your computer and use it in GitHub Desktop.
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 System.Linq; | |
using UnityEngine; | |
public class AutoReferencer<T> : MonoBehaviour where T : AutoReferencer<T> { | |
#if UNITY_EDITOR | |
// This method is called once when we add component do game object | |
protected new virtual void Reset() | |
{ | |
// Magic of reflection | |
// For each field in your class/component we are looking only for those that are empty/null | |
foreach (var field in typeof(T).GetFields().Where(field => field.GetValue(this) == null)) | |
{ | |
// Now we are looking for object (self or child) that have same name as a field | |
Transform obj; | |
if (transform.name == field.Name) | |
{ | |
obj = transform; | |
} | |
else | |
{ | |
obj = transform.Find(field.Name); // Or you need to implement recursion to looking into deeper childs | |
} | |
// If we find object that have same name as field we are trying to get component that will be in type of a field and assign it | |
if (obj!=null) | |
{ | |
field.SetValue(this, obj.GetComponent(field.FieldType)); | |
} | |
} | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment