- Home /
How do I spawn a prefab where I click?
what I mean is, I need to spawn a prefab where on the screen that I click, such as if I click on the upper right hand corner it should spawn there, as of now they spawn in the same place every time right above the player
Answer by dragonking300 · Mar 13, 2017 at 11:14 PM
//Look at this script and learn from it
using UnityEngine;
using System.Collections;
public class ClickSpawnScript : MonoBehaviour
{
public GameObject Prefab;
public int RayDistance = 10;
private Vector3 Point;
public LayerMask Whatever;
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Make Whatever a Raycast layer or if you don't want it just exclude it
if (Physics.Raycast(ray, out hit, Whatever.value))
{
Point = hit.point;
Instantiate(Prefab, Point, Quaternion.identity);
}
}
}
}
NP, also, accept my answer so people don't see this
Answer by SnStarr · Mar 13, 2017 at 07:09 AM
Do this..
Public GameObject myPrefab; //Assign this in inspector or in code for whatever prefab you want instantiated.
void Update()
{
if(Input.GetMouseButtonDown(0)) //If we click left mouse button
{
Vector3 instantiatePosition = Input.mousePosition; //Setting a reference to our mouse position in a vector3
Gameobject newGameObject = Instantiate(myPrefab, instantiatePosition, Quaternion.identity) //Creating a reference to our prefab and instantiating at the mouse position
newGameObject.name = "MyObject"; //This will name the object instead of it instantiating as Clone
}
}
Thanks for the help but there's still a problem, it spawns them quite a ways off in the distance and not on screen, but it does actually spawn not just in the same space anymore
@SnStarr Thanks for the help but there's still a problem, it spawns them quite a ways off in the distance
Your answer
![](https://koobas.hobune.stream/wayback/20220612113044im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Can you name something that you spawned with a spawner script? 1 Answer
(C#)Place GameObject from Mouse 0 Answers