- Home /
How to Spawn Prefab on Mouse Click
This might seem straight forward but its more complex than the title explains.
This is a two player Asymmetric VR(HTC Vice) and PC game. The HTC is listed as the Main Camera looking around the world and the player on the PC using the monitor, mouse and keyboard needs to be clicking around the scene placing targets where an explosion prefab spawns killing the bad guys.
I am using Raycast to check the click of the mouse but I am having trouble telling it not to use the Main Camera which is default to the VR. I have separate Displays being called on start up but I'm not sure how to set the PC player screen to receive the raycast clicks because right now i think its going off the VR and my prefab is spawning all over in random spots.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateTargetLocation : MonoBehaviour
{
public GameObject prefab;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Left mouse clicked");
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name == "floor")
{
Instantiate(prefab, hit.point, Quaternion.identity);
print("My object is clicked by mouse");
}
}
}
}
}
Answer by Anton-Korhonen · Dec 19, 2017 at 08:39 AM
Camera.main is a reference to the first camera which is tagged "MainCamera". You can e.g. store a reference to the non-VR camera in-editor and then call raycast from it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateTargetLocation : MonoBehaviour
{
public Camera nonVRCamera;
public GameObject prefab;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Left mouse clicked");
RaycastHit hit;
Ray ray = nonVRCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name == "floor")
{
Instantiate(prefab, hit.point, Quaternion.identity);
print("My object is clicked by mouse");
}
}
}
}
}
Just drag-and-drop your non-VR camera to the nonVRCamera field and you should be good to go. Your problem can be solved multiple ways - this is just one example.
Ah thank you. I tried Camera.ad$$anonymous$$Camera cause i declared that up top earlier but didn't like it so thank you for the help. There are not a lot of resources on the Asymmetrical game play since its pretty new but if anyone who reads this has any links they would like to share please do. @Anton-$$anonymous$$orhonen Thank you.
Your answer
Follow this Question
Related Questions
know when GVR raycaster is looking at nothing 1 Answer
Am I using the PlayerSettings.virtualRealitySupported check wrong? 0 Answers
How can i run a Unity Build on my PC, but use my phone as second screen, (Cheapskate Oculus-Like) 2 Answers
How to make UNITY multiplayer with two HTC VIVE in the same real room? 0 Answers