Instanteate prefab

Hi guys, i would like to know how can i instanteate a prefab from my player to to place where i mouse click, i find some answers but all of them or almost all are from 2D games… If someone can help me i will appreciate. Ty.

Look into ray-casting from the camera:

1 Like

My problem is not create a ray or instantiate the prefab but moves the prefab to the point where i mouse click…

When you create the ray, you use a Physics.Raycast(), which will return a Hit variable that tells you where, in 3D space, the ray from your mouse hit a 3D object. That will allow you to instantiate your prefab at the 3D object you clicked on in your scene.

var ObjectToCreate:GameObject;
var cameraMain :Camera;
function Start () {

}

function Update () {

var screenPos = Input.mousePosition; /* position z,y/
screenPos.z = 10;   /*how  far  should  it  be  created from  the   orgin point ?*/
var worldPos = cameraMain.ScreenToWorldPoint(screenPos);

var clone:GameObject;
if(Input.GetMouseButtonDown(0)){
        var cloneObject:GameObject;
        cloneObject=Instantiate( ObjectToCreate, worldPos, Quaternion.identity);}

}


}

Best regards:)

1 Like

Ty m8, now, can anyone convert this to c# plz? xD

  • GameObject ObjectToCreate;
  • Camera cameraMain ;
      • void Update () {
    • Vector3 screenPos = Input.mousePosition; /* position z,y/
  • screenPos.z = 10; /how far should it be created from the orgin point ?/
  • Vector3 worldPos = cameraMain.ScreenToWorldPoint(screenPos);
    • GameObject clone;
  • if(Input.GetMouseButtonDown(0)){
  • GameObject cloneObject;
  • cloneObject=Instantiate( ObjectToCreate, worldPos, Quaternion.identity);}
    • }}

check it if works

i get an error in screenPoz.z=10; it dont know wt is “z”

int screenPos —> Vector3 screenPos

missed that :slight_smile:

for coding in a text editor sans compiler, you did excellently!

No errors but this instantiate the prefab in my mouse position… wt i need is to instantiate in my player and move to mouse position click …

from player to click position.

  • if(Input.GetMouseButtonDown(0)){ cloneObject=Instantiate( ObjectToCreate, Player.tansform.position,Quaternion.identity); /* this will create object at player’s position*/
    • cloneOjbect.transform.Translate(cloneOjbect.transform.position,worldPos,speed*Time.dletaTime);
1 Like

i get an error in the line saying that Translate need to be (float, float, float)

cloneOjbect.transform.Translate(cloneOjbect.transform.position,worldPos,speed*Time.dletaTime);

Make that cloneObject.transform.positoin = Vector3.Lerp (…) instead?