Samrat Luitel
Samrat Luitel

Reputation: 379

Instantiate Object at mouse position

I have created a script which was supposed to instantiate gameobject according to mouse position but something has went wrong. And it is only being instantiated at one position and in the middle of the screen.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LineInstantiater : MonoBehaviour {

    public GameObject lineprefab;
    private GameObject linehandler;
    private Vector3 mousepos;

    void Update(){
        if (Input.GetMouseButton (0)) {
            mousepos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            linehandler = Instantiate (lineprefab,Camera.main.ScreenToWorldPoint(Input.mousePosition),Quaternion.identity) as GameObject ;
            linehandler.transform.position = mousepos;
        }
    }

}

Please tell me what is wrong with my script.

Upvotes: 1

Views: 8053

Answers (1)

Programmer
Programmer

Reputation: 125245

The problem is that Input.mousePosition does not have z-axis because there is only x and y axis for mouse coordinate. The z axis is simply 0 therefore returning wrong position when Camera.main.ScreenToWorldPoint is used.

You need to do Input.mousePosition;, manually modify it's z-axis value to be anything > 0. Usually, 10 is fine for this but you can modify it if it is not enough for you. After that, you can then pass that modified Vector3 to the Camera.main.ScreenToWorldPoint(mousepos) function.

public GameObject lineprefab;
private GameObject linehandler;
private Vector3 mousepos;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        mousepos = Input.mousePosition;
        mousepos.z = 10;

        mousepos = Camera.main.ScreenToWorldPoint(mousepos);
        linehandler = Instantiate(lineprefab, mousepos, Quaternion.identity) as GameObject;
    }
}

OR

public GameObject lineprefab;
private GameObject linehandler;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);
        linehandler = Instantiate(lineprefab, rayCast.GetPoint(10), Quaternion.identity) as GameObject;
    }
}

Not related:

I noticed that you are using Input.GetMouseButton. You probably want Input.GetMouseButtonDown as Input.GetMouseButtonDown is called once until the key is released. Input.GetMouseButton is repeatedly called when the pressed key is held down and you can easily create thousands of objects with that.

Upvotes: 5

Related Questions