Reputation: 23
I am new to Unity Game Development and I find the following usage in code a bit confusing.
private Transform enemy;
// Start is called before the first frame update
void Start()
{
enemy = GetComponent<Transform>();
}
According to the documentation GetComponent() is a public function. So how can this be accessed without being instantiated? I found a similar question was asked on Unity's community but I didn't find any of the answers answering the question exactly to the point. Please help me in understanding this. The link to question on Unity forum is below. Question
My Unity version is 2018.4.16f1 Thanks!
Upvotes: 1
Views: 493
Reputation: 90630
Your class most probably inherits from MonoBehaviour
which inherits from Behaviour
which inherits from Component
.
Component
implements GetComponent
Fazit: The instance which you are calling this method on is no other than this
, the instance Start
is called on.
Btw for Transform
there is already a dedicated property Component.transform
so you should not use GetComponent
for getting a Transform
reference.
Upvotes: 2
Reputation: 11
you are calling the GetComponent() method of the GameObject you added your MonoBehavior to and assign it to the Transform enemy. It is even the first Answer from your linked Question.
Upvotes: 1