DarkRewar/BaseTool

Add AutoField<T> to retrieve components automatically

Opened this issue · 1 comments

Create class that retrieves by GetComponent the field it is looking for when code needs to access it.

public class MyComponent : MonoBehaviour
{
    public AutoField<Rigidbody> Rigidbody;

    public void Start()
    {
        // will retrieve rigidbody automatically if not found
        Rigidbody.velocity = transform.forward;
    }
}

Two problems:

1 - How do we access the component from the AutoField<T>?

Let's admit that AutoField<T> could be like this:

 [Serializable]
 public class AutoField<T> where T : Component
 {
     [SerializeField]
     private MonoBehaviour _parent; // How do we get it?

     private T _value;
     public T Value
     {
         get
         {
             if (_value == null)
             {
                 _value = _parent.GetComponent<T>();
             }
             return _value;
         }
     }

     public AutoField()
     {
         // maybe we can access parent object here? But how?
     }
 }

2 - How do we access direct properties by calling the AutoField<T>.[Value]?

On option was to create an implicit operator, but it doesn't seem to work...

public static implicit operator T(AutoField<T> instance) => instance.Value;

image