Hey guys I’ve got another problem,
script A has a local var p : transform;
script B wants to dynamically alter script A’s p variable (determine what type of prefab p uses). How to I pass the parameter from script B to script A?
script A and script B are in different game objects. (script B is in a UI button, script A is in an object that spawns p)
thx.
You can use GetComponent to get an object’s script, and alter that script’s variables. A shortcut is to define the object by using the script’s name as a type instead of GameObject (or Rigidbody or whatever). For example, if you use this as “script B” on the UI button:
Script B:
var otherObject : ScriptA;
function Start () {
var otherObjectClone = Instantiate(otherObject);
otherObjectClone.someVariable = "Remote control!";
}
And say the following script, which we’re calling “ScriptA”, is attached to the spawned object. (And it literally must be called “ScriptA”, unless you change the first line of Script B to use some other name. Otherwise you get an error message about not having a valid type.)
ScriptA:
var someVariable = "default text";
function Start () {
print (someVariable);
}
If that object is instantiated normally, it will print “default text”. If, however, it’s instantiated by Script B, it will print “Remote control!” Even though you have typed the object by script name instead of GameObject, you can still use transforms and so on…like “otherObjectClone.transform.position = Vector3(20,20,20);” would still work.
Hopefully that makes sense.
If you’d rather use GetComponent, though, the principle is still the same. It’s just another line of code. Here’s Script B using GetComponent:
Script B:
var otherObject : GameObject;
function Start () {
var otherObjectClone = Instantiate(otherObject);
var otherObjectScript = otherObjectClone.GetComponent(ScriptA);
otherObjectScript.someVariable = "Remote control!";
}
–Eric
Thanks eric!
Just finished reading the codes.
The instantiating part might be a bit confusing though. I actually planned to have multiple ScriptA game objects placed across the game world.
ScriptB in the UI button is actually like a toggle to determine what objects SpawnA gameobjects should spawn.
Here’s the codes for the scripts, maybe it might help clarify what I’m doing (or doing wrong):
This is scriptA (inside the object spawner):
var selection : Transform; // variable to be used by scriptB
function OnMouseDown () {
StartCoroutine ("SpawnIndicator");
}
function SpawnIndicator () {
var q = transform.position;
q.y=3;
Instantiate (selection, q, Quaternion.identity);
}
This is scriptB (inside UI Button):
var otherObject : ScriptA; // having the object named as ScriptA as well
var newselection : Transform; //new prefab to replace selection variable at scriptA
function OnMouseDown () {
var otherObjectClone = Instantiate(otherObject);
otherObjectClone.selection = newselection;
}
thanks,
chris.