I have enemy character, script of this object has speed, gravity and so on. Then there are “movement” function is separate script. I want to reduce number of parameters of this function. And try to make function to get access to script(to receive speed, gravity values from the script), which attached to object.
But what, if this function is called in body of many different scripts. How to get script which call the function? I provide current GameObject to this function as parameter, but still cannot understand how to get access to script(not knowing it’s name) knowing the object, which has required script attached. I hope, I describe my problem clear enough.
Thanks
I'm pretty sure you have to know the name of the Script. How do you even do that? Not knowing the name? O.o
You definitely must know the script name! In Unity, the script name becomes its type - without quotes or extension. The script “MoveEnemy.js”, for instance, will originate the type MoveEnemy after compiled - and the compiler must know this type to know which variables and functions it has, of which type etc.
Assuming you know the script name (suppose it’s MoveEnemy) and the object it’s attached to (let’s suppose it’s referenced by the variable gObj), you can get a reference to the script doing this:
var script: MoveEnemy = gObj.GetComponent(MoveEnemy);
// use the reference as if it was the script itself:
script.gravity = 500; // smash the enemy with a neptunian gravity!
Only the instance of MoveEnemy attached to the object referenced by gObj will be affected.
EDITED: After a second reading of your question, I understood that you want the Movement(gObj: GameObject) to get the script and read some variables - am I right? Anyway, you must know the script name to do that. If you have several scripts with different names in these objects, you can try to pass the script type as a string parameter and get it inside Movement:
function Movement(gObj: GameObject, type: String){
var script = gObj.GetComponent(type);
var g = script.gravity;
...
}
What I’m not sure is if the untyped script variable will know exactly which type it was assigned to, and thus be able to find the variable gravity or any other - you must test this.
if i understand your question correctly then you know which gameobject has your script, so just select the gameobject by clicking on it in the scene view or the hiearchy, and all the scripts attached should be in the inspector, just double click on your script to open it.
I'm pretty sure you have to know the name of the Script. How do you even do that? Not knowing the name? O.o
– SisterKy