A Better GetComponent() Method

At some point, I found myself writing the following code:

C#

See how quickly it can get very annoying and repetitive very fast? So, the obvious solution was to write a more functional and generic GetComponent<>() method. Here is what I did:

C#

And my ChceckComponents() method was quickly reduced to this:

C#

Check out the GitHub repo and let me know if you have any suggestions or ideas for the next post!

2 thoughts to “A Better GetComponent() Method”

  1. Hiya!

    Alternatively, you could add the following attribute to the class definition:

    [RequireComponent(typeof(BoxCollider))]
    public class TestScript : MonoBehaviour {
    //…
    }

    The editor will now force you to always have that component together with the TestScript.

    Once you know the component is guaranteed to be there, you could use serialized private variables:

    [SerializeField] private BoxCollider col_1;
    void Reset() {
    col_1 = GetComponent(); //tnx to RequireComponent, this will always work
    }

    1. That’s true! I’m actually using this method as well. Thanks for the addition 🙂

      PS: Perhaps I should add this method to the the post as well 🙂

Comments are closed.