I’m currently writing workaround over standard MonoBehaviour. I have a similar code:
public GameObject gameObject;
public Transform transform;
void OnValidate() {
gameObject = GetComponent<GameObject>();
transform = GetComponent<Transform>();
}
transform works just fine, but gameObject returns none/null! But if I replace gameObject with _gameObject in example, or remove assignment OnValidate and assign in inspector by myself it works! Is it bug or something?
UPD: So, how to get current GameObject without using this.gameObject?
GameObjects aren’t Components. If you need a reference to the GameObject that your script is attached to, just use this.gameObject. You can also get the transform by using this.transform, since all components (including your scripts) have access to the transform of the gameobject they are attached to.
System.Type t = typeof(GameObject);
Debug.Log(GetComponent(t));
it gives me the exception:
ArgumentException: GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface.
So, when we look at the inheritance chain, we see that the GameObject does not inherit from either MonoBehaviour or Component or is an interface. But when it comes to Transform, we see that it derives from Component. That’s why GetComponent with Transform works. MonoBehaviour also derives from Component and GetComponent with MonoBehaviour works. At the bottom is always System.Object. Even when it comes to the interfaces.
GameObjects are not Components and cannot be retrieved with GetComponent<>(). You can assign it in the inspector because then the inspector knows to look for a GameObject. If you want the GameObject that your script is attached to, then just use this.gameObject.