- Home /
Block Placement Help
How do I modify this script so that instead of creating a standard cube, it instead creates a prefab, which can be specified from within the inspector? For example, instead of creating a cube when the button is clicked, it creates a building, or a tree, or a sherbet lemon.
var distance = 5;
function OnGUI ()
{
if (GUI.Button(Rect(25,25,100,30), "Place Block"))
{
var newCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
newCube.transform.position = transform.position + transform.forward * distance;
newCube.transform.rotation = transform.rotation;
}
}
Answer by chronicfail · Jul 31, 2013 at 06:36 PM
Try adding a variable at the top "var prefab : Transform" and replacing the whole newCube section with something like:
var newPrefab=Instantiate(prefab,transform.position+transform.forward*distance,transform.rotation);
That will set position and rotation of the prefab at the same time, also.
Thanks, it works. Although, I'm having a problem with my prefab spawning in the air, and although it has a rigidbody, it either hovers in the air or falls through the terrain, depending on whether I lock the y position or not.
That's wierd, but sounds more like a problem with your prefab. Does it have a collider attached and if it does, have you made sure that the "isTrigger" box is not selected? Also, if your prefab is using a mesh collider, that will not work with rigidbodies unless "convex" is selected.
Ok, thanks for the info. How would you add a downward transform to the newPrefab? Because if I could do that, then I could set it up so that it always is placed on the ground? $$anonymous$$aybe get the height of the spawned object above the ground, and transform it downwards that much?
If you put a script on the prefab with something like this:
function Start () {
var hit : RaycastHit;
if(Physics.Raycast(transform.position,Vector3.up*-1,hit){
var hitDistance=Vector3.Distance(transform.position,hit.point);
transform.translate(0,-hitDistance,0);
}
}
it would raycast directly downward, and, if there was an object underneath, move it down to the point where the raycast intersects with the object underneath.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
In-World Placement Help 1 Answer
Quick Custom Inspector Question 1 Answer
Unity Networking, connecting to sever problems :( 1 Answer
What is wrong with this? 1 Answer