Hi can anyone point me to or tell me what code to use if say I have a cube in my scene and i want it to run an animation when i click it? I know how to do this with gui but not with a actual 3d object in unity like a plane or something? Thanks (:
You could use OnMouseDown, or Raycast to do this, be sure to have a collider of some type on the object for either.
OnMouseDown example in C#
Attach this to the object you want detected:
using UnityEngine;
using System.Collections;
public class OnMouseDownExample : MonoBehaviour
{
void OnMouseDown()
{
print (name);
}
}
Raycast example in C#
attach this to any object. Just to make sense, attach to the main camera or an empty.
using UnityEngine;
using System.Collections;
public class RaycastExample : MonoBehaviour
{
Ray ray;
RaycastHit hit;
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
if(Input.GetMouseButtonDown(0))
print(hit.collider.name);
}
}
}
You raycast from the click position (mouse or touch etc), then if you hit an object you want to interact with run whatever code you need.
For starters look at:
You can use a layer mask for Physics.Raycast so you only check the objects you are interested in, or you could use RaycastAll etc.
Use the OnMouseDown function in a script, and attach the script to the object.