Codo
Codo

Reputation: 562

Unity GameObject OnclickEvent

Hello people I have following class in unity, not attached to anything:

public class Path : MonoBehaviour, IPath
{
 public GameObject Quad { get; set; } 
 public Guid Id { get; set; }

 public Path( float sizeX, float sizeY)
 {
     Quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
     Id = Guid.NewGuid();
     Helpers.ChangeSize(Quad, sizeX, sizeY);
 }
}

It is called on runtime.

I want to set an OnClick Event on the GameObject Quad (or on this class) which calls the method of another instace of a class (which is attached to the main camera) and sends its Id to it.

Any idea how to do that?

Upvotes: 0

Views: 191

Answers (1)

Seth Setse
Seth Setse

Reputation: 345

If you want to detect a click on a game object you'll need to use a raycast whenever the player clicks.

if (Input.GetMouseButtonDown (0)) {    
         var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;

         if (Physics.Raycast(ray, out hit, 100)) {
             // whatever tag you are looking for on your game object
             if(hit.collider.tag == "Idk") {                         
                 //Call method on camera                      
             }
         }    
     }

You'd have to put this into an update method somewhere. Preferably some sort of InputManager. You can read about the Raycast Here

Upvotes: 1

Related Questions