[solved] Instantiate prefab at mouse position

Hallo,
I´m trying to instantiate a prefab at mouse position. My script compiles without error,

using UnityEngine;
using System.Collections;

public class InstantiatePrefabAtMouse : MonoBehaviour
{
    public GameObject Boje;
   
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Debug.Log("Mouse is down");

            RaycastHit hitInfo = new RaycastHit();
            bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
           
            if (hit)
            {
                GameObject BojeInstance;
                BojeInstance = Instantiate(Boje, hitInfo.point, Quaternion.identity) as GameObject;
               
            }
        }
    }
}

But when I click in my scene I get the following error:

3900241--332062--error001.JPG

What did I do wrong ?

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?

1 Like

Thanks thats what I was missing :), I added the script to a parent of the main camera :(.
Now it works.

1 Like