- Home /
How to Instantiate GameObject on top of collider? (C#
So I want to be able to instantiate a gameobject into the scene by the click of the mouse. I have it all figured out except one part, how would I make the instantiate 'origin point' to be the bottom of the gameobject, not the middle. Because when I spawn in objects, it looks like it's instantiating them from the middle, making the object intersect and look weird. I just want to be able to place objects on top of other colliders, no intersecting involved.
Here's my C# code:
void Update () {
if (Input.GetMouseButtonDown(0)) {
//Creates the raycast hit variable
RaycastHit hit;
//Creates the ray variable, set to origin at the center of the camera that the script is attached too
Ray ray = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
//Starts the logic: if the raycast hits a collider, it will spawn (Instantiate) the prefab
//obj is the prefab
//hit.point is the location in which the ray collided
if (Physics.Raycast(ray, out hit)) {
if (hit.collider != null) {
Instantiate(obj, hit.point, Quaternion.identity);
}
}
}
}
Answer by robertbu · Aug 20, 2014 at 04:00 AM
You can use an empty game object as a parent. The empty game object would be position at the place you want to move the pivot, and placement script would use the empty game object. There is also the SetPivot script in the Unity Wiki.
@robertbu I tried and it didn't work. After all, how would I be able to move the empty gameobject to a different position without moving my cube(gameobject)?
How about making your empty game object a child of your cube? This way you can move your game object anywhere without moving your cube and when you move the cube the empty game object will move along with it.
... then you get the empty with
Vector3 pos = transform.getComponentInChildren().position;
and finally you Instantiate at the "pos" position
Since you can do that:
hit.transform.GetComponentInChildren<Transform>().position;
yes ;)
Answer by Cherno · Aug 20, 2014 at 01:47 PM
Since you have declared the prefab to instantiate, you can use it's collider's y size and y offset to find out at which y position the new gameObject has to be instantiated.