Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...