I’m trying to figure out the best way to do the following:
I have an object in the scene. When the user clicks on this object, I want it to spawn another object (a cube) somewhere else in the screen.
So far, I can get the cube to spawn within the clickable object itself with the following code:
var cube = GameObject.Find("OrangeCube");
function OnMouseDown () {
Instantiate(cube, transform.position, transform.rotation);
}
Can anyone help? I understand it involves creating a Gizmo (which I was able to do), but I’m not sure how to link the two, or write the code that says “spawn the cube where the gizmo is”
Thanks in advance!
With the code you posted you are spawning the object at exactly the same position and rotation of the object you click on. No need to create a Gizmo or anything like that. Just give the Instantiate function a position and rotation of where you want it to spawn.
var cube = GameObject.Find("OrangeCube");
function OnMouseDown ()
{
var distance = 5.0;
var randPos : Vector3 = Random.onUnitSphere + transform.position * distance;
Instantiate(cube, randPos, Random.rotation);
}
The code above will spawn your cube a distance of 5 units from the gameObject you have this script attached to in a random direction.
Thankyou! That’s so much easier to handle than what I thought I had to do.
I’ve been playing around with the code to try and get it to spawn in a specific location. For example, higher on the y-axis.
My code is as follows:
var startingPoints: Vector3;
startingPoints = Vector3(transform.position.x,transform.position.y,transform.position.z);
var cube = GameObject.Find("OrangeCube");
function OnMouseDown ()
{
var distance = 1.2;
transform.position.y = transform.position.y + distance;
Instantiate(cube, startingPoints, transform.rotation);
}
What that code does, is move the object I’m clicking on up the y-axis.
What I was aiming to do, was take the original co-ordinates of the clickable object, increase the ‘y’ co-ordinate and place my cube in that new position.
Sorry if it’s a really obvious thing to do - coding really isn’t my strongest asset!
Thanks again.
quick monday morning bump 
Try this :
var distanceIncrement : Vector3 = Vector3 (0, 1.2, 0);
var cube : GameObject = GameObject.Find("OrangeCube");
function OnMouseDown () {
Instantiate(cube, transform.position + distanceIncrement, transform.rotation);
}
Thanks! I can get that working much better now.