Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have this code attached to a 3D cylinder game object. I plan to use it as an arrow and rotate it when clicked and dragged. I had no idea what do as I am a beginner so I started with adding an onClick listener to a Button component on the Cylinder, and wrote this script which I added as component to the cylinder.. But the Rotate() function isn't called when I click on it, as there is no message in the Log.. This is the code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MoveAim : MonoBehaviour {

    public bool isAiming;
    private Button button;


    void Start () {
        isAiming = true;
        button = GetComponent <Button>();
        button.onClick.AddListener (Rotate);
        Debug.Log ("Start!");
    }

    void FixedUpdate () {
    }
    void Rotate() {
        Debug.Log ("Click recorded");
    }

}

Any idea what to do? And how should I implement the rotation of the cylinder? Help would be appreciated!

Thanks!

share|improve this question
up vote 4 down vote accepted

You are using a button, which is an UI element. It is not supposed to be used on 3d objects in the game world.

On 3d objects in game world you probably want to use IPointerClickHandler. They work like this:

using UnityEngine;
using UnityEngine.EventSystems;

public class Clickable : MonoBehaviour, IPointerClickHandler
{
  public void OnPointerClick( PointerEventData eventData )
  {
    Debug.Log ("Click recorded");
  }
}

Also note that the object should have a collider attached to it, and the scene must have EventSystem and Standalone Input Module attached to some object.

There are more events supported to allow different behaviours.

share|improve this answer
    
Thanks for the answer, but I just realised that I could use void OnMouseDown() on the object. However, is that not recommended? – SinByCos yesterday
    
You can use whatever suits your needs. Using EventSystem is usually more flexible and it lets you do more things. – Lasse 12 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.