- Home /
Release Mouse button doesent turn script enabled=true again
Hey! I want to let a plane rotate until a certain degree when i raycast/press on a gameobject with a Tag x and when i release the mouse button the plane should snap back to its original position. the code looks like this now:
using UnityEngine;
using System.Collections;
public class rotati : MonoBehaviour {
public GameObject maze;
public string tag;
public float lastAngle;
void Update() {
if (Input.GetMouseButton(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100)) {
if(hit.collider.tag == tag) {
maze.transform.rotation *= Quaternion.Euler(0, 0, 20 * Time.deltaTime);
if(lastAngle < 20 && maze.transform.rotation.eulerAngles.z >= 20)
enabled = false;
lastAngle = maze.transform.rotation.eulerAngles.z;
Debug.Log("---> Hit: ");
}
}
}
if (!Input.GetMouseButton(0)){
enabled = true;
maze.transform.rotation = Quaternion.Lerp(maze.transform.rotation, Quaternion.identity, 0.15f);
Debug.Log("released left click.");
}
}
}
but my problem is, that i can not rotate the plane/gameobject (maze) again becaue the script doesent turn on again after releasing the mouse button, could somebody tell me why?
Answer by LazyElephant · Dec 10, 2015 at 06:48 PM
Because the script is being disabled, once you press your mouse button for the first time, your script will stop running and will be unable to turn itself back on. You will have to enable it again from a separate script.
Answer by callen · Dec 10, 2015 at 07:04 PM
Like LazyElephant says, the Update() method is not called when a script is disabled, but you can use other methods to do the same work, namely OnMouseDown and OnMouseUp. They are still called on disabled scripts. If I understand the logic you posted, something like this should give you the same effect, with simpler code:
using System;
public class rotati : MonoBehaviour
{
public GameObject maze;
//public string tag;
float lastAngle;
bool mouseIsDown = false;
void OnMouseDown()
{
mouseIsDown = true;
Debug.Log("---> Hit: " + gameObject.name);
}
void OnMouseUp()
{
mouseIsDown = false;
Debug.Log("released left click.");
}
void Update()
{
if (mouseIsDown)
{
//rotate 20 deg/second
maze.transform.rotation *= Quaternion.Euler(0, 0, 20 * Time.deltaTime);
//when angle is 20 degrees, stop rotating
if (lastAngle < 20 && maze.transform.rotation.eulerAngles.z >= 20)
mouseIsDown = false;
}
else //return angle to 0 degrees
maze.transform.rotation =
Quaternion.Lerp(maze.transform.rotation, Quaternion.identity, 0.15f);
lastAngle = maze.transform.rotation.eulerAngles.z;
}
}
Your answer
Follow this Question
Related Questions
How do I get the player to correctly rotate toward the mouse? 1 Answer
Make player face same direction as camera. 4 Answers
Turning character with transform.Rotate 0 Answers
transform.lookat() limitation... 1 Answer
Is There An OnMouseStop? 0 Answers