Search Unity

[solved] Instantiate prefab at mouse position

Discussion in 'Scripting' started by Achim, Nov 17, 2018.

  1. Achim

    Achim

    Joined:
    Dec 19, 2007
    Posts:
    199
    Hallo,
    I´m trying to instantiate a prefab at mouse position. My script compiles without error,

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class InstantiatePrefabAtMouse : MonoBehaviour
    5. {
    6.     public GameObject Boje;
    7.    
    8.     void Update()
    9.     {
    10.         if (Input.GetButtonDown("Fire1"))
    11.         {
    12.             Debug.Log("Mouse is down");
    13.  
    14.             RaycastHit hitInfo = new RaycastHit();
    15.             bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
    16.            
    17.             if (hit)
    18.             {
    19.                 GameObject BojeInstance;
    20.                 BojeInstance = Instantiate(Boje, hitInfo.point, Quaternion.identity) as GameObject;
    21.                
    22.             }
    23.         }
    24.     }
    25. }
    But when I click in my scene I get the following error:

    error001.JPG

    What did I do wrong ?
     
  2. Karrzun

    Karrzun

    Joined:
    Oct 26, 2017
    Posts:
    129
    Your code looks fine so I assume there's something wrong in the inspector. Maybe your camera is missing the "Main Camera" tag or something?

    Also, just to be sure: does your Debug.Log fire?
     
    Achim likes this.
  3. Achim

    Achim

    Joined:
    Dec 19, 2007
    Posts:
    199
    Thanks thats what I was missing :), I added the script to a parent of the main camera :(.
    Now it works.
     
    ashkanaral likes this.