How to stop a rotating object on pointer enter?

I am working with this VR application where I have this rotating globe that I want to stop when the reticle pointer enter or hover on it and then will continue on rotating once the on reticle pointer exit. I did try using this code that I found here also:

public class stopRotation : MonoBehaviour {

public bool rotateObject = true;
public float speed = 5f;

void Update(){
		transform.Rotate (0, speed, 0);
}

void OnPointerEnter(){
	rotateObject = false;
}

void OnPointerExit(){
	rotateObject = true;
}

}

Originally its function was OnMouseOver and OnMouseExit, it worked but then when I ran it on my android phone, the stop rotation didn’t work. So I changed function to OnPointerEnter and OnPointerExit but it didn’t work. Please help.

OnPointerEnter is for UI elements. You should use OnMouseEnter and OnMouseExit.

To use OnPointerEnter etc you must add the Interface for it to work.

Something like in here


(This answer was written as of Unity 2017.3.1.)

Hi @gllybeean ! So, there’s a couple of things here:

  1. The boolean rotateObject that you’ve defined is not controlling any logic. You need to make running transform.Rotate(0, speed, 0); in the Update() loop dependent upon rotateObject being true.

  2. OnPointerEnter and OnPointerExit depend upon your class implementing the IPointerEnterHandler and IPointerExitHandler interfaces from UnityEngine.EventSystems.

All in all, here’s what your script should look like:

using UnityEngine;
using UnityEngine.EventSystems;    // you need this for pointer events

public class stopRotation : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler    // inherits from pointer event interfaces in addition to just being a simple MonoBehaviour that does everything a basic Unity script does
{
    public bool rotateObject = true;
    public float speed = 5f;
 
    void Update()
    {
        if (rotateObject)    // this is the same as saying "if (rotateObject == true)"
        {
            transform.Rotate (0, speed, 0);
        }
    }
 
    public void OnPointerEnter(PointerEventData eventData)    // you don't need to know anything about the pointer event, just that it happened.
    {
        rotateObject = false;
    }

    public void OnPointerExit(PointerEventData eventData)    // so although you get an object of type PointerEventData passed to you when this happens, you can ignore it.
    {
        rotateObject = true;
    }
}