Why do I have to use GetComponent() function?

I don’t understand the usage of GetComponent() even after reading the documentation.

In an example I followed, they used transform.parent.GetComponent() in the script of a GameObject to access its parent.

Since every GameObject has a transform property, and suppose if I want to get something within the hierarchy of the GameObject called MyObject, I could just use transform.parent. But in the tutorial, they use transform.parent.GetComponent(), where ParentOfMyObject is the script name of MyObject’s parent.

As transform.parent is going to be the same as GetComponent, why even have to use the function GetComponent? I feel that I am missing something out.

use GetComponent to get a SCRIPT that is attached to something

say you have something like en enemy … happyEnemy

say there’s a SCRIPT attached to happyEnemy, called ‘MakeFire’



that’s how you get that SCRIPT (called ‘MakeFire’) which is attached to happyEnemy

OK ?

so if you want to get at a SCRIPT attached to anything, use GetComponent

(that will get you started - there are other ways to use it as well but that is 90% of the usage)

if you want to get at a SCRIPT attached to anything, use GetComponent

(They could have called it “GetScript” for the sake of making it easier for beginners to learn the whole system - heh! - since the vast majority of usage is to get a script, and as a beginner you’ll only ever use it to get a script. Furthermore, as a beginner you’re desperately trying to figure our “how the £$@ do I get a script?!” - indeed, that’s the key insight, “GetComponent” encompasses the idea “Get A Script”)

Note, this can also apply to “you”. Say there is a hero. Say you are a script “EatOften” which is attached to the hero. Say there is ANOTHER script attached to the hero, perhaps “FindTrees”. So you are EatOften. You want to get to FindTrees, in that case you simply say GetComponent(FindTrees)

Easy, right?

Note - in al cases, when you use GetComponent there are NO, repeat NO quotation marks around the name of the script inside the brackets.

Most of the time you don’t have to use it, and indeed shouldn’t use GetComponent if it’s possible to assign the reference to the component (usually a script) in the inspector. If your object is already part of a parent-child hierarchy, and the script on one gameobject needs to access a component on another you can drag on the reference(s), make it a prefab and when you instantiate the prefab it will come into the world with the component already “got.”

You only need to use it in situations where the component you’re getting does not exist at the start of the game, for example, if you have a “DontDestroyOnLoad()” setup object that needs to persist through all levels:

var scriptVar : ScriptName;
var newThingy : GameObject;
function OnLevelWasLoaded("_MyFirstLevel")
    newThingy = GameObject.FindWithTag("GameThingy");
    scriptVar = newThingy.GetComponent.<ScriptName>() as ScriptName;