Search Unity

Object OnMouseDown?

Discussion in 'Scripting' started by merlinmarijn, May 30, 2016.

  1. merlinmarijn

    merlinmarijn

    Joined:
    Aug 3, 2015
    Posts:
    44
    How do i place it on a empty object and use that to see what objects i clicked? without placing the script on every object i need it to check?
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    You could use a raycast from the camera instead, its far more efdicient than a csript on every gameovjext
     
  3. matta1989

    matta1989

    Joined:
    May 20, 2013
    Posts:
    27
    Im kind of lost myself.

    So lets say I make this

    InputFactory.cs
    Code (CSharp):
    1.  
    2.  
    3. Public class InputFactory : Monobehaviour, IPointerClickHandler
    4.  
    5. public void OnPointerClick(PointerEventData eventData)
    6. {
    7. Debug.Log("Clicked");
    8. }
    9.  
    10. //Loads of other clicks handled
    Now I want this one object to handle all clicks keyboard buttons and etc.

    How do i get it to register clicks on an object in the screen, because the Debug.Log only works when i have the script attached to it.
     
  4. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    This one only works on the object the script got attached to, because it's sort of like an onMouseDownOverThisObject thingy, if you want to register clicking on any object without putting one of these codes on every single one, then use a raycast from the camera like this:
    Code (CSharp):
    1. //if your camera is he main camera:
    2. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    3. HitInfo hit;
    4. if (Physics.Raycast(ray, out hit)) {
    5.    now your clicked gameObject is hit.gameObject
    6. }
    or use an eventhandler
     
  5. matta1989

    matta1989

    Joined:
    May 20, 2013
    Posts:
    27
    Okei so no point in looking further into that then! Thanks

    I thought that the new unityevent system would be integrated in a manner that it allowed it to be more user friendly like that.

    But I guess i have to make my own

    Code (CSharp):
    1. OnLeftMouseDown()
    2. {
    3. if(Input.getMouseButtonDown(0)){
    4.  
    5. //Implement your code here
    6.  
    7. }
    8. }
    thanks for the help, really appreciate it gorbit99