Rotating Object When Clicked and Rotating Back When Clicked Again C#
I've been working on a project where I'm essentially making a flashlight. I need to screw the base of the flashlight on in order for it turn on, so I was wanting to have the user click the base to cause this action. I started by importing a 3D model I made and all of its wraps, rather than making the model directly in Unity.
I'm new to Unity, but I have been watching tutorials and looking through help forums -- I just can't seem to get this to work. My code doesn't have any compiler errors, but the base isn't rotating when I click on it during game mode. Any idea or suggestions would be good! My entire script is below, and I do have the object tagged appropriately.
using UnityEngine;
using System.Collections;
using System.Collections,Generic;
public class OnOff : MonoBehavior {
private Ray ray;
private RaycastHit hit;
void Update() {
GameObject OnOffSwitch = GameObject.FindGameObjectWithTag("OnOffSwitch");
if(Input.GetMouseButtonDown(0) && OnOffSwitch.transform.position.y == -90f) {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (ray, out hit)) {
if(hit.collider.tag == "OnOffSwitch") {
transform.Rotate (new Vector3 (0f, 20f, 0f));
}
}
} else if(Input.GetMouseButtonDown(0) && OnOffSwitch.transform.position.y == 0f){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (ray, out hit)) {
if(hit.collider.tag == "OnOffSwitch") {
transform.Rotate (new Vector3 (0f, -90f, 0f));
}
}
}
}
}
Answer by w029bnw · Jun 08, 2017 at 05:22 PM
I eventually solved the problem myself.
Here is the code should anyone else need something similar:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class OnOff : MonoBehaviour {
void OnMouseDown() {
GameObject OnOffSwitch = GameObject.FindGameObjectWithTag ("OnOffSwitch");
if (OnOffSwitch.transform.eulerAngles.y >= 0.5 && OnOffSwitch.transform.eulerAngles.y <= 0.6) {
OnOffSwitch.transform.Rotate (0, 0, -90);
} else if (OnOffSwitch.transform.eulerAngles.y >= 270 && OnOffSwitch.transform.eulerAngles.y <= 271) {
OnOffSwitch.transform.Rotate (0, 0, 90);
}
}
}