void Update()
        if (Input.anyKey)
            foreach (Transform child in go.transform)
                if (Input.inputString == child.name)

I want to Instantiate the gameobjects with a space between each one that i will set with public variable. And that the gameobjects position will start from the 0,0,0 of the terrain.

For example like that:

Objects with gap


The problem you're trying to solve just takes a little math and the definition of a few configuration variables.

Vector3 intialPosition = new Vector3(0,0,0); //The initial position you want to start at
Vector3 spacingOffset = new Vector3(0,1,0); //The desired space between GameObjects
int index = 2; //The n-th (from 0) GameObject in the line to place

//Gets the offset of size in the same axis as your spacing offset
Vector3 sizeOffset = this.gameObject.GetComponent<MeshRenderer>().bounds.size * spacingOffset.normalized;
//Computes the vector from initial position to n-th GameObject
//(spacingOffset * index) = contribution from spaces
//(sizeOffset * index) = contribution from the size of the GameObjects
//(spacingOffset * index) + (sizeOffset * index) simplifies to the below...
Vector3 vectorFromInitial = (spacingOffset + sizeOffset) * index;

//Final position is computed for n-th cube as follows
this.gameObject.transform.position = intialPosition + vectorFromInitial;

The only mysterious property might be MeshRenderer.bounds.size which is the size of your GameObjects mesh in world space. Everything else was just visualizing the problem and picking out the variables to put together to get the desired value.

Note that this breaks for a spacingOffset that is not axis aligned where it would be more appropritate to use a BoundingSphere. Also, if the objects are not all the same size or have different origins, this also breaks and requires more complex logic to get the size of each one individually.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.