Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Drawing game objects at the mouse cursor

Discussion in 'Scripting' started by npoguca, Aug 8, 2014.

  1. npoguca

    npoguca

    Joined:
    Aug 7, 2014
    Posts:
    25
    How do I draw a prefab exactly where my mouse is right now? I could really use the code to do that because I've been on it for like a day and still got nothing.
     
  2. NomadKing

    NomadKing

    Joined:
    Feb 11, 2010
    Posts:
    1,461
  3. npoguca

    npoguca

    Joined:
    Aug 7, 2014
    Posts:
    25
    The thing is, I'm totally new to Unity and I was hoping for more of a step-by-step solution.
     
  4. bitoffdev

    bitoffdev

    Joined:
    Aug 12, 2013
    Posts:
    43
    This code should show you how to place a prefab at the mouse pointer. Read all the comments to understand what is going on.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ExampleClass : MonoBehaviour {
    5.  
    6.     public GameObject prefabObj;
    7.  
    8.     //places a prefab at the mouse position
    9.     void PlacePrefab() {
    10.         //First you will want to get the mouse position using Input.mousePosition
    11.        Vector2 mousePos = Input.mousePosition;
    12.        //Next you will want to convert the Vector2 mouse position to a Vector3 world position
    13.        Vector3 worldPos = Camera.main.ScreenToWorldPoint (new Vector3 (mousePos.x,mousePos.y,Camera.main.nearClipPlane));
    14.        //Finally you will want to place your prefab
    15.        Instantiate(prefabObj, worldPos, Quaternion.identity);
    16.     }
    17.  
    18.     //Places a prefab on mouseup
    19.     void OnMouseUp() {
    20.         PlacePrefab();
    21.     }
    22. }
     
    NomadKing likes this.