I’m trying to figure out how to spawn a prefab where the camera is looking and when a ui button with a certain tag is pressed. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Spawner : MonoBehaviour {
private Vector3 _Position;
public GameObject Prefab;
void OnEnable(Button other)
{
if (other.CompareTag("Cube"))
{
GetPosition();
Instantiate(Prefab, _Position, Quaternion.identity);
}
}
private void GetPosition()
{
Vector3 mousePosFar = new Vector3(
Input.mousePosition.x,
Input.mousePosition.y,
Camera.main.farClipPlane);
Vector3 mousePosNear = new Vector3(
Input.mousePosition.x,
Input.mousePosition.y,
Camera.main.nearClipPlane);
Vector3 mousePosF = Camera.main.ScreenToWorldPoint(mousePosFar);
Vector3 mousePosN = Camera.main.ScreenToWorldPoint(mousePosNear);
RaycastHit hit;
if (Physics.Raycast(mousePosN, mousePosF - mousePosN, out hit, 1000))
_Position = new Vector3(hit.point.x, hit.point.y, hit.point.z);
}
}