- Home /
Click on cube to Debug.Log
Hi
I am learning Unity3D so i am absolute beginner in this. I have plane (as ground), on plane i have cube with colider and rigidbody and then i have firstperson controller. I want to go with FPC (firstperson controller) to a cube and click on it with left button on mouse and i expect, that gives me a log in console. Script is attached to cube.
Thanks for help
My script code:
#pragma strict
function OnMouseDown() {
Debug.Log("Left Click");
}
Answer by OrdinaryDev83 · Aug 02, 2015 at 12:59 PM
Use a Raycast using the cursor position from camera to far away:
#pragma strict
var hit : RaycastHit;
//The range of the raycast
var raycastRange : float;
var actualCamera : Camera;
function Update () {
var ray : Ray = actualCamera.ScreenPointToRay (Input.mousePosition);
//Debug the ray in green
Debug.DrawRay(ray.origin, ray.direction * raycastRange, Color.green);
if(Physics.Raycast (ray, hit, raycastRange)) {
if(Input.GetMouseButtonDown(0)){
Debug.Log("Touched " + hit.collider.name);
//You can use tag for it
if(hit.collider.tag == "YourTagHere"){
Debug.Log("Touched " + hit.collider.name + " with the " + hit.collider.tag + " tag.");
}
}
}
}
Attach this script to camera.
I tried this solution using Raycast, but doesn't work. I deleted all old scripts on cube, wrote new one with this code, attached is to camera on firstperson controller and nothing. Nothing happend...anyway thanks for reply
EDIT : I added a new variable for selecting THE first person camera, if you use multiples cameras.Test now :) EDIT 2:Have you change the raycast range...? x) set it to 1000 to start.
Your answer
Follow this Question
Related Questions
Only Allow One Click on GameObject? 2 Answers
Making A Debug.Log depending on what GameObject is active 1 Answer
How do I select a group full of sprites, between two points? 1 Answer
Why my OnMouseDown is lost?!!! 0 Answers
Wondering if I can modify Unity to work better for 1 specific game. 0 Answers