- Home /
Calling a function from a different script on the same object
Okay, this goes down to OOPdesign, maybe, but say I've developed two independent scripts, in this case, Gravity and a player controller. I add both to a gameobject, and one of the features of the game controller dynamically alters the gravity script variables (think: tractor beam, basically I increase my gravity range, and then temporarily change the mass of my rigidbody)
My question is, what is the best way to call a function in another script that is on the same object?
I got it working by going something like this.SendMessage("SetGravityRange",1000);
but is that the right way to do it? It doesn't feel quite right, and while I don't want to combine it in the same class, I kind of feel like I should be able to do a using Gravity; or Gravity.SetGravityRange(1000); sort of thing (realising that neither of those work).
Does anyone have any thoughts? Thanks, Mike
Answer by Mike 3 · Oct 05, 2010 at 02:08 PM
You'd use GetComponent to get a reference to your other script
In javascript:
GetComponent(Gravity).SetGravityRange(1000);
http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Components.html
Thanks, sorry to be asking questions when clearly I should be reading the manual more carefully!