- Home /
question about instantiating
so i'm making a game where farming is a mechanic, and to do that i made a few cubes that i use as plots of land. shown here -
and i would like to make it so that when i click on one, it creates an object on top of it, such as this (done in the editor) -
now i have mouse input setup, but i still need to figure out how to create the object. this is where i've been coding -
i just need to know how to pull it off with instantiate, and the main problem i'm having is positioning it at the clicked farm plot. any help would be greatly appreciated!
Answer by asafsitner · Jul 10, 2013 at 06:27 AM
Consider using **`OnMouseDown`** instead of doing a raycast. To actually create the object you'll need to call **`Instantiate`**.
Here is an example:
//this script is attached to the Farm object
var FieldObject : Transform; //this is set in the inspector
//this function will be called whenever the user clicks on the Farm
//IMPORTANT: in order for this function to be called, the Farm object must have a Collider component attached
//since you're using square fields, I suggest using a box collider
function OnMouseDown ()
{
//the following call will create a FieldObject at the pivot point of this Farm object with the default rotation
Instantiate (FieldObject, transform.position, Quaternion.identity);
}
The important piece of code here is the Instantiate
call, as that's the one that creates objects.
Answer by robertbu · Jul 10, 2013 at 06:21 AM
Since all your pink blocks are the same size, you can just move up a set distance (I'll call 'dist') on the 'y':
var pos = hit.transform.position;
pos.y += dist;
Instantiate(prefab, pos, Quaternion.identity);