In Unity csharp, I want to make a GetOrAddComponent method, which will simplify the respectives GetComponent and AddComponent (for no good reason I suppose).
The usual way is this:
// this is just for illustrating a context
using UnityEngine;
class whatever : MonoBehavior {
public Transform child;
void whateverMethod () {
BoxCollider boxCollider = child.GetComponent<BoxCollider>();
if (boxCollider == null) {
boxCollider = child.gameObject.AddComponent<BoxCollider>();
}
}}
Right now I could make this class . . . :
public class MyMonoBehaviour : MonoBehaviour {
static public Component GetOrAddComponent (Transform child, System.Type type) {
Component result = child.GetComponent(type);
if (result == null) {
result = child.gameObject.AddComponent(type);
}
return result;
}
}
. . . So this works:
// class whatever : MyMonoBehavior {
BoxCollider boxCollider = GetOrAddComponent(child, typeof(BoxCollider)) as BoxCollider;
But I wish I could write it like this:
BoxCollider boxCollider = child.GetOrAddComponent<BoxCollider>();
The only idea I could come up with would be way too complicated to do it (replacing each Transform with a MyTransform) and thus not worth the trouble of even trying. At least not just for a nicer syntax.
But is it? Or is there any other way this could be achieved?
Have you tried using Extension Methods? You can declare them like this:
You can call it like an instance method, then:
See the link above for more details on extension methods.