- Home /
Question by
matthewcastiglia · Jan 04, 2017 at 10:00 AM ·
raycastonmousedown
OnMouseButtonDown Raycast multiple Objects
I am trying to apply onmousebuttondown that works with raycast. Those two work fine. However, when I apply the script to multiple objs, any collider hit affects all objects with the script attached. I want only the object hit by the raycast to appear/disappear.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class reflectorclickaction : MonoBehaviour {
private enum ReflectorState {Initial, Visible, Rotate};
private ReflectorState myState;
protected Animation Animation;
RaycastHit hit;
protected void Awake()
{
Animation = GetComponent<Animation>();
}
void Start() {
myState = ReflectorState.Initial;
}
void Update() {
if (myState == ReflectorState.Initial) {
state_Initial();
}
else if (myState == ReflectorState.Visible) {
state_Visible();
}
else if (myState == ReflectorState.Rotate) {
state_Rotate();
}
}
void state_Initial() {
myState = ReflectorState.Initial;
gameObject.GetComponentInChildren<Renderer>().enabled = false;
gameObject.GetComponentInChildren<MeshCollider>().enabled = false;
if (Input.GetMouseButtonDown(0)) {
Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rhInfo;
bool didHit = Physics.Raycast(toMouse, out rhInfo, 500.0f);
if (didHit) {
Debug.Log(rhInfo.collider.name + " -- " + rhInfo.point);
myState = ReflectorState.Visible;
Debug.Log("State is set to Visible.");
}
else {
Debug.Log("No Object Hit");
}
}
}
void state_Visible() {
gameObject.GetComponentInChildren<Renderer>().enabled = true;
gameObject.GetComponentInChildren<MeshCollider>().enabled = true;
if (Input.GetMouseButtonDown(0)) {
Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rhInfo;
bool didHit = Physics.Raycast(toMouse, out rhInfo, 500.0f);
if (didHit) {
Debug.Log(rhInfo.collider.name + " -- " + rhInfo.point);
myState = ReflectorState.Rotate;
Debug.Log("State is set to Rotate.");
Animation.Play("ReflectorRotate", PlayMode.StopAll);
}
else {
Debug.Log("No Object Hit");
}
}
}
void state_Rotate() {
if (Input.GetMouseButtonDown(0)) {
Ray toMouse = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rhInfo;
bool didHit = Physics.Raycast(toMouse, out rhInfo, 500.0f);
if (didHit) {
Debug.Log(rhInfo.collider.name + " -- " + rhInfo.point);
myState = ReflectorState.Initial;
Animation.Play("ReflectorRotateBack", PlayMode.StopAll);
Debug.Log("State is set to Initial");
}
else {
Debug.Log("No Object Hit");
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
OnMouseButtonDown raycast 2 Answers
Raycasting and Triggers Issue 1 Answer
Raycasting not working on my colliders 1 Answer
How to count numbers on onmousedown? 1 Answer
Multiple objects with OnMouseDown 2 Answers