- Home /
Error : Transform.parent not working properly.
I have a script attached to my "Land" GameObject which spawn obstacles at different random co-ordinates, this is the main script.
var cube : GameObject;
function Start () {
var newCube = Instantiate(cube, Vector3(Random.Range(-22, 22), 7.5, Random.Range(transform.position.z-4,transform.position.z+4)), Quaternion.identity);
}
it works properly, but i want to make these obstacles child of their respective "Land" so i added this to the script and finally it becomes,
var cube : GameObject;
function Start () {
var newCube = Instantiate(cube, Vector3(Random.Range(-22, 22), 7.5, Random.Range(transform.position.z-4,transform.position.z+4)), Quaternion.identity);
newCube.transform.parent = gameObject.transform;
}
but the problem is it starts spawning more than 1 obstacle per land, which is un-intended,
here are the screenshots,
Before adding newCube.transform.parent = gameObject.transform;
After Adding it.
i cant figure out the problem itself, why it duplicates my blocks.
Note :- One Land Object Spawns one Block, and there are 6-7 land blocks in the above images.
To what object is the script attached? It looks like you're duplicating each successively generated land object rather than instantiating them from an untouched prefab.
actually i am duplicating the land, and from that land creating a obstacle, to create a infinite world
i want to have only one block under each of the land, but its generating more than one
Answer by NickP_2 · Nov 04, 2014 at 01:07 PM
Instatiate transforms, not gameobjects :)
So the prefab property 'cube' should be a transform! new code:
var cube : Transform;
function Start () {
var newCube = Instantiate(cube, Vector3(Random.Range(-22, 22), 7.5, Random.Range(transform.position.z-4,transform.position.z+4)), Quaternion.identity);
newCube.parent = gameObject.transform;
}
@NickP_2: That won't change anything. It doesn't matter if you instantiate a GameObject or a component of that gameobject as it will always instantiate the whole gameobject including all components and childs.
However in most cases it's more convinient to use Transform ins$$anonymous$$d of GameObject, but it won't change the behaviour at all, just the return type ;)
Strange, I had similar problems and it was because I instantiated gameobjects ins$$anonymous$$d of transforms. Ah too bad.
thanks @Bunny83 you were able to find the exact mistake i was making..