How can I spawn where I click?

Hi there!

I want to click on a GameObject that “activates” the spawn and then click again in another GameObject and spawn the object where I clicked (The last time). (Sorry for bad explanation, my english is pretty bad…)

I’ve got this code, that makes spawn the prefab on the 1st GameObject, I don’t even know how to begin.

public class InstancePlayer : MonoBehaviour {

	public GameObject player;
	int i = 0;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

	}

	void OnMouseDown() {
		if (Input.GetMouseButtonDown(0) && (i<11)){
				Instantiate(player, transform.position, Quaternion.identity);
				Debug.Log ("Player:" + i);
				i++;
		}
	}
}

Thank you!

  • Cast a ray from your camera center towards on button press
  • From ray hit you can get/set any information on any gameobject
  • If ray hit object is “Activator” (easiest would be set a tag), then activate some value that you can spawn now, that value can be simple boolean
  • If you press a button and boolean value is true - spawn it on ray hit position.