- Home /
where is the difference? (js-scripting)
Hi there :) I got two questions but I think they are in the same 'main question'... where is the difference between GameObject.SendMessage(FunctionName) and GameObject.FunctionName? and between GameObject.Component and GameObject.GetComponent(Component)? So, the only thing I know is, that you aren't able to call all components and in no way scripts with the shorter way. Is GameObject.Component only shorter for often used Components? thanks ;)
I don't know for sure myself so this might not be 100% correct. Send$$anonymous$$essage addresses any script of your gameObject. If you have two scrips say enemyHealth.js and playerHealth.js and both have the function ApplyDamage( dmg: float). If you use Send$$anonymous$$essage("ApplyDamage", 10) ApplyDamage will be called no matter which script your gameObject has. If you used gameObject.enemyHealth.ApplyDamage(10) you get a nullreference if the gameObject has the playerHealth script. However calling a function directly is cheaper than Send$$anonymous$$essage since Send$$anonymous$$essage will look in all scripts until it found the function ApplyDamage.
For the GetComponent I have no idea myself. I usually use GetComponent to define a shortcut variable like :
var target : Transform;
var targetHealth : enemyHealth;
function Start(){
targetHealth = target.GetComponent(enemyHealth);
}
Note that there also is the GetComponents[] GetComponents<>; method which will return all specified components of your gameObject.
The short answer is that GetComponent retrieve the actual object and 'directly call' the desired method, Send$$anonymous$$essage use reflection over all scripts and invoke all methods with the given name. A direct call (GetComponent) is much more efficient and that approach is to be favored where possible, imo.
Answer by SarperS · Sep 19, 2012 at 05:09 PM
SendMessage calls the method you give in the parameter on every script of the gameobject, GameObject.FunctionName points to a method in GameObject class, the methods you can call that way are coded into the GameObject classs by Unity.
GameObject.Component is the same, there are some built in properties in GameObject class, referencing the rigidbody, collider etc. with GetComponent() method you can find other components and your custom scripts.
So in short, GameObject.GetComponent() or GameObject.transform are internal (not to be confused by the C# access modifier) methods and properties of the GameObject class but GameObject.GetComponent() returns your custom components you add to the gameobject.