UnityContrib / framework

Unity Contribution Framework
MIT License
8 stars 2 forks source link

Selector component #4

Closed robintheilade closed 9 years ago

robintheilade commented 9 years ago

Quite often you will find yourself writing code that finds objects based on component, tag name or their game object name. Other times you write code that only allows for design time assignment. Most of the time the code works as expected however the code is often found in multiple components.

What if you could just add another component to your components that would be responsible for finding the object you need and let the component concentrate on what it does best?

This is the aim of the Selector component.

An added benefit of using selectors is that the selection is centralized, which is good when your selection algorithm changes. Then you only need to change the algorithm in one location.

Here is an example of code that allows for designer to assign the transform at design time. That won't do as well with run time assignment.

public class CameraController : MonoBehaviour
{
    [SerializeField]
    private Transform player;

    private void Update()
    {
        this.transform.position = this.player.position + Vector3.up * 5.0f;
    }
}

Here is another example that works at run time. Not generic enough though.

public class CameraController : MonoBehaviour
{
    private Transform player;

    private void Start()
    {
        this.player = GameObject.FindObjectWithTag("Player");
    }

    private void Update()
    {
        this.transform.position = this.player.position + Vector3.up * 5.0f;
    }
}

And here is an example of what it might look like with a selector. The playerSelector field is assigned at design time. Now the CameraController no longer only supports design time or transforms with "Player" tag.

public class CameraController : MonoBehaviour
{
    [SerializeField]
    private Selector playerSelector;

    private void Update()
    {
        var player = this.playerSelector.Selected;
        this.transform.position = player.position + Vector3.up * 5.0f;
    }
}

This is in essence what I want to add to the framework. Any suggestions and questions are welcome.

/Robin

robintheilade commented 9 years ago

Thought about calling it a locator instead of selector, but I'm afraid it would be mistaken for Service Locator pattern.

robintheilade commented 9 years ago

Here is the WIP branch for the selector https://github.com/UnityContrib/framework/tree/feat/issue-4/selector-component

robintheilade commented 9 years ago

Merged with master