- Home /
Instantiate object basics (Unity 3.2, C#)
Hi all. Having some problems with Instantiating an object into the game world. Nothing fancy. Ultimately, I would like to click on a GUI Button and that will instantiate a node object that attaches to the mouse pointer to create a simple "select and drop" mechanic.
But need to learn how to walk first before running... I made a prefab of a cylinder called "Node". I have some script attached to my Main Camera to handle the game's GUI. All I want at this point is to click on a button to spawn an instance of the Node prefab into the world. Here's some code:
public class ElementsHUD : MonoBehaviour {
public GameObject Node;
// Display buttons void OnGUI() {
GUILayout.BeginArea (new Rect (Screen.width/2 - 200, Screen.height/2 + 100, 300, 300)); GUILayout.Box (textOutput); GUILayout.EndArea ();
if (GUI.Button(new Rect(100, 300, 100, 20), new GUIContent("Node 1")))
{
GameObject objNode = Instantiate(Node, transform.position, transform.rotation);
}
My main concern is how do I get the script to reference the cylinder prefab I have sitting in the Hierarchy? Secondary concern is how to instantiate this cylinder at a specific vector? Sorry this seems like a very basic question but would appreciate any pointers.
Thank you!
Answer by Jason B · Mar 30, 2011 at 01:14 AM
Since Node is public, looking at the script in the inspector should show a field for "Node". To put a prefab in it, either drag and drop the prefab into it or click the little circle to the right and pick from the list.
Also, you might need to put (GameObject)
before Instantiate
in your code, or it might throw you an error. Like this:
GameObject objNode = (GameObject)Instantiate(Node, transform.position, transform.rotation);
If you need the object at a specific vector, you can either create the vectors from scratch in your instantiation...
GameObject objNode = (GameObject)Instantiate(Node, new Vector3(0,0,0), transform.rotation);
...or you can create a variable up top and plug in a value for it from the inspector.
public Vector3 placementspot;
Something like that, and then use:
GameObject objNode = (GameObject)Instantiate(Node, placementspot, transform.rotation);
Thanks Jason, that was very helpful! The syntax is a bit unfamiliar to me in terms of putting "(GameObject)" in front of the Instantiate expression. But yeah, before I was getting this error:
error CS0266: Cannot implicitly convert type UnityEngine.Object' to
UnityEngine.GameObject'. An explicit conversion exists (are you missing a cast?)
In any case, it's something I can read up on. Now on to the next step of spawning my node cylinders to the mouse pointer! Thanks again.