- Home /
How can I get the position of transforms inside an instantiated game object?
Context: Placing customizable guns on a customizable base vehicle.
I have a game object with a script attached. The script contains variables for the base model and the guns model.
var baseFile : Transform; var gunFile : Transform;
function Start(){ // create base mesh newBaseModel = Instantiate(baseFile, transform.position, transform.rotation);
// make a gun and position it
gunLocator = newBaseModel.Find("gunLocation");
print(gunLocator); // This line prints out fine
print(gunLocator.position); // This line errors out
newGun = Instantiate(gunFile, gunLocator.position, gunLocator.rotation);
newGun.localScale = gunLocator.localScale;
newGun.parent = transform;
}
This is all that's in my scene. When I hit play, I get the error:
NullReferenceException
VehicleBuilder.Start() (at Assets\Scripts\VehicleBuilder.js:11)
Once playing, I can look at my instantiated vehicle in the hierarchy, expand it out and find the "gunLocation" locator, and the line that prints properly prints out UnityEngine.Transform.
Any ideas why I can't access the position of the locator in an instantiated object?
Answer by Mike 3 · Jun 24, 2010 at 09:39 PM
It's not finding a transform, it's just sending back null, and the javascript compiler is fooled because it thinks gunLocator is supposed to be a Transform (and theres some weird voodoo which lets js print out Transform instead of null in cases like this)
My guess is that your gunLocation object is not a direct child of newBaseModel - if it's not, that function won't find it
It's path based, not search
If you need to search through the children, the easiest way is to make a quick recursive function
$$anonymous$$y prefab for the vehicle had an extra node between the model and the prefab's root. Removing that solved the problem as the model was now a the piece being instantiated, not the game object above the model. Thanks for the tip!