How do I instantiate gameObjects?

Hi guys,
New Unity user here and also new to Programming in it… Thanks for taking the time to read this :slight_smile: I have totally no idea if my code is right but basically I’m trying to create an object to appear when I click my mouse - and I want it to appear where I click. After researching a while this is what I eventually came up with:

#pragma strict
 var camper : GameObject;
 function Update () {
		if (Input.GetMouseButtonDown(0)) {
		var mousePos : Vector3 = Input.mousePosition;
		mousePos.z = 49.9f;
		mousePos = Camera.main.ScreenToWorldPoint(mousePos);


     Instantiate(camper, mousePos, Quaternion.identity);
    
	}
	}

Could someone verify that this code is right and if not, help me out a little? What this has done for me is when I’m in Play Mode, if ‘var camper’ is set to be an Asset, it works! But I don’t want it to be an Asset because the only ones I have are construction worker and character controller which means when I build it, it takes me into that view. When I set it to a Game Object such as a cylinder, click… nothing happens…

So all that leads to my big question: Can I somehow make a game object appear when I click? Or could I make an asset that is a game object?
What would actually be the best is if I click and just a small black 2d square appears onto my sphere where I click- but I don’t know how to do this and if not possible it’s ok.

I would really be appreciative if a Unity Pro or anyone who has more experience with unity and programming than me could help me. Any suggestions to improve my code would be very appreciated and any help would be awesome.

Thanks a heaps guys

If you want a small black 2d square to appear, I would suggest making a quick 2-poly squad in your modeller, import it into your project view and give it a black material.

You then link this asset to the camper slot in this script from the inspector.

If you’ve created a cylinder through Unity it exists only in the scene view not the project view which is probably why you cannot instantiate it.

Remember assets are just collections of meshes, animations, textures etc, once they are in the game worlds they become game objects that contain the contents of those assets as components.

you can create a simple prefab of an asset you want to create…

then create a public GameObject object and assign the prefab to the script(in the properties)…

then you can call instantiate the GameObject object that you had created, as many times as you’d like…

I’m a novice myself, but i think this should work :slight_smile: