- Home /
Referencing gameObject from script after Instantiate
I've created a prefab which contains both a valid mesh and a javascript. In the javascript (jsInstantiatedObj) I have something like this:
function GoRight(){
iTween.MoveBy(gameObject, [just parameters..]);
}
I then instantiate a few of those in an empty GameObject, let's call it ObjMgr. Inside ObjMgr's javascript I do something like this:
function MoveEverythingToTheRight(){
var types = GameObject.FindGameObjectsWithTag("myValidTag");
for(var go : GameObject in types)
go.GetComponent(jsInstantiatedObj).MoveRight();
}
But at runtime I receive a: NullReferenceException: Object reference not set to an instance of an object Which is being thrown by the jsInstantiateObj script when trying to access gameObject. If, instead of calling jsInstantiateObj.MoveRight(), I write exactly what should be executed in the method, I have no problems at all.
Do you know why can't I access gameObject from the script attatched to the instantiated prefab? Thanks!
Just an idea: When does your managerscript gather it's managed objects? Check calling FindGameObjectsWithTag in Start() to ensure all sub-objects are already loaded.
Not actually an answer, but is it on purpose that the example has the GoRight() function and that you're calling $$anonymous$$oveRight() on it?
Just checking, are you sure that the gameObject property is the one throwing the exception, not some internal code of iTween.$$anonymous$$oveBy? To test you could do something like:
var go = gameObject;
iTween.$$anonymous$$oveBy(go, [just parameters..]);
...