- Home /
In-World Placement Help
I made a script, shown here, that is attached to a gameobject. It creates a gui button on the top left that, when clicked, creates a cube in front of the player. However, when I press the button, it does not place the block, but upon spawning in there is a block a little ways away from the player. Help?
Sorry, here it is.
var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
public var distance = 5;
function OnGUI () {
if (GUI.Button(Rect(25,25,100,30), "Place Block")) {
Instantiate(cube, transform.position + transform.forward * distance, transform.rotation);
}
}
Answer by clunk47 · Jul 29, 2013 at 10:21 PM
If you want to instantiate an object, it's usually best to use a prefab. What you are doing here is creating a cube primitive from script when your script wakes up, then duplicating it. A much better way to do this with CreatePrimitive, is just create the cube when the button is pressed without even using Instantiate. Here is an exmaple that should resolve your issue.
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;
}
}
Worked perfectly on my end. I attached it to my main camera, clicked the button, and a cube appeared 5 units in front of me.
Ahh, you added it to the main camera. I added it to my character. That was where I ****ed up.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Gameover function calling before game ends help 2 Answers
Beginner need some help on Card Game 2 Answers
Block Placement Help 2 Answers
GUI controlling other game objects 0 Answers