Basically i have a script written to where i have a gameobject and i have a simple 2x4 wood cube/model attached to it. I dont understand why when i click it spawns that object where the camera is and not where im pointing… All help is appreciated thanks
Heres my code
public GameObject Wood;
public bool isWood = true;
public GameObject Metal;
public bool isMetal = false;
public Transform spawn;
RaycastHit hit;
public GameObject target;
// Use this for initialization
void Start () {
target = Wood;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)){
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
if (Physics.Raycast(ray)){
}
Instantiate(target, ray.origin, Quaternion.identity);
}
}
Theres more code than that but all the other code is unnecessary to include.
I dont get any errors this just doesnt work.
Actually, I got it working without having to cast a ray.
The trick is to pass the INVERSE z position of your camera in the ScreenToWorldPoint last argument. So if your camera’s z position is -10, pass 10. Here’s my C# code:
using UnityEngine;
using System.Collections;
public class MousePick : MonoBehaviour {
public GameObject cuber;
void Update() {
if (Input.GetButtonDown("Fire1")) {
print(Input.mousePosition);
Vector3 p = Camera.main.**ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,10.0f));
print(p);
print(p.x);
print(p.y);
Instantiate(cuber,new Vector3(p.x,p.y, 0.0f),Quaternion.identity);
}
}
}
That’s because you Instantiate the objects at the ray’s origin, i.e. the camera in your case as it’s the object shooting the ray. You want to add hitInfo and spawn the object at hitInfo.point.
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0), out rayInfo))
{
Instantiate(target, rayInfo.point, Quaternion.identity);
}
}
I also don’t understand why you put the Instantiate call outside the if statement’s block so I put it back in. If it’s a mistake ignore it.