example(2)
function OnMouseDown()
{
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
}.
i want to click an object and it do an action like rotate or translate,
the example (1) do the action no matter were i click,
and the example (2) just don’t work
well, my question is how can i click on an object an do an action, i know how rotate works, but i want to click only an object, cause no matter what part of the screen i click it always do the action and that is my problem
Note that both of these (Input.GetMouseButtonDown() and OnMouseDown()) will only fire once for the single frame that the mouse is down. If you want continuous motion while the mouse is down, use Input.GetMouseButton() or for example #2, use OnMouseDrag(). Note that the OnMouse*() methods require the object you click on to have a collider and the collider must the the front-most collider.
ok but how can i do that, i mean how can i clic exactly on an object an make an action, cause no matter where i click on the screen the object always do the action, i want to clic exactly on an oject and do an action, how?
You can do it one of two ways. First OnMouseDown() will only be called if you click on the collider of the object that has the script. So if you use OnMouseDown() and are getting clicks off the object, it means you have a collider issue (the collider is too big and/or not aligned to the object). The second way is to check the name or the tag after you have done the Raycast(). After the raycast you can do something like: if (hit.collider.name == "Button") { // Do whatever you want } "Button" here is a placeholder for whatever you named your object(s).
A RayCast can be used to return the object clicked, I think this may be what your looking for:
using UnityEngine;
using System.Collections;
public class RaycastClickExample : MonoBehaviour {
void Update() {
float turnSpeed = 45.0f;
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
if (hit.transform != null) {
Debug.Log("Hit " + hit.transform.gameObject.name);
hit.transform.Rotate(Vector3.up * turnSpeed);
}
}
}
}
Here it is in UnityScript, as that’s the form you used in your samples:
#pragma strict
class RaycastClickExample : MonoBehaviour {
var : turnSpeed : float = 45.0;
function Update () {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
if (hit.transform != null){
Debug.Log("Hit " + hit.transform.gameObject.name);
hit.transform.Rotate(Vector3.up * turnSpeed);
}
}
}
}
}
Please note that for this to work, there must be a Collider for your RayCast to hit attached to any object you intend to click.
Please format your code
– Benproductions1