- Home /
Getting a reference to a class created in a different gameObject (Javascript)
In a script in Object A I do the following:
var prefab : GameObject; var myObj : CustomGameObject;
var temp : GameObject = Instantiate (prefab, transform.position , transform.rotation);
We'll call the instantiated gameObject Object B. In Object B's Awake function I do this:
childObj = new ChildCustomGameObject(gameObject);
ChildCustomGameObject extends CustomGameObject, both are declared in another file. Now in Object A, immediately after Instantiating Object B, I want to say myObj = childObj. But I want to do this without having to actually know the name of the script attached to Object B, nor the name of the derived class of CustomGameObject. I figured SendMessage was perfect, so I tried this in Object A:
temp.SendMessage("GetCustomObject", myObj)
Which called in Object B:
function GetCustomObject(obj : CustomGameObject)
{
obj = childObj;
}
But it doesn't work. When I look at Object A's myObj in the inspector, it looks like it created its own instance of CustomGameObject, and all the properties inside it are null.
So how can I get myObj from Object A to be a pointer/reference to a class rather than a instance of a class? And how can I get it to point to childObj from Object B? Is this possible in Javascript?
Answer by Mike 3 · Jun 13, 2010 at 11:59 PM
Javascript doesn't have the ability to do ref or out parameters like c#, which would make this work pretty easily
The easiest way I can think of getting it working is to send a reference to the GameObject the first script is on when calling GetCustomObject, and call thatGameObject.SendMessage("SetCustomObject", childObj);
Worked like a charm. Thanks! Shame Javascript doesn't have something so simple as ref parameters.