- Home /
How to spawn GameObject exactly on top of another object?
Working on a 2D game in Unity and I'm having difficulties trying to spawn a block exactly on top of a platform in my game. I don't want the block to look like it's floating or overlapping the platform.
I can't seem to get the calculation correct.
I currently have this code:
public GameObject blockPrefab;
public GameObject platform;
public GameObject dummyBlock;
// Use this for initialization
void Start ()
{
float platformSize = platform.GetComponent<Renderer>().bounds.size.y;
float blockSize = dummyBlock.GetComponent<Renderer>().bounds.size.y;
Debug.Log(platformSize.ToString());
GameObject test = (GameObject)Instantiate(blockPrefab,
new Vector3(platform.transform.position.x, platform.transform.position.y + blockSize, platform.transform.position.z),
Quaternion.identity);
}
The problem with this is that it spawns the block in a way that it overlaps the platform which means my calculation for the block's y position is wrong. I also tried adding the platformSize instead of the blockSize and it spawns the block way above the platform.
I'm still getting used to working with Unity's world coordinate system, so yeah. Anybody know how to solve this?
Any help is appreciated!
Not sure if this is right, but I think the transform.position of your platform is at the center of your object. If you then add the blocksize to the Y coordinate, you get the y value of the CENTER of your platform + the blocksize. Which means that the part above the center of your platform isn't accounted for. That's why the block overlaps. So theoretically you need to add half of the platform size to the Y of your factor.
new Vector3(platform.transform.position.x, platform.transform.position.y + blockSize + platformSize /2, platform.transform.position.z)
I think this will work..
Thanks for the comment. It gave me an idea. In addition to the code you provided, I had to divide blockSize by 2, but I got it working now!
Copy your comment as an answer and check as "answered"???
Your answer
![](https://koobas.hobune.stream/wayback/20220613195502im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
portal problem 1 Answer
Spawning System 1 Answer
Wrapping the visible world? 1 Answer
Navmesh agent teleporting 3 Answers