Search code examples
c#unity-game-enginegoogle-cardboard

Generate ClickMouseButton(0) anywhere on display


Here is my script:

void Update () {
    public float clickTimer = 2f;
    clickTimer -= Time.deltaTime;
    if(clickTimer <= 0){
        //"Generate Click" I try: Input.GetMouseButtonDown(0);
        clickTimer = 2f;
    }
}

I don't want to click any specific object because I have RayCastHit and I want to generate click anywhere on display.


Solution

  • With this script (which is for 2D games) you can create a RayCast from the point in the screen where you clicked with the mouse, and check what GameObjects you have hit. I recommend you to tag first any GameObject you want to be clicked

    void Update () {
    
        clickTimer -= Time.deltaTime;
    
        if(clickTimer <= 0){
    
            if(Input.GetMouseButtonDown(0)) {
    
                //What point was pressed
                Vector3 worldPoint = Camera.main.ScreenToWorldPoint( Input.mousePosition );
                worldPoint.z = Camera.main.transform.position.z;
                //Generate a Ray from the position you clicked in the screen
                Ray ray = new Ray( worldPoint, new Vector3( 0, 0, 1 ) );
                //Cast the ray to hit elements in your scene
                RaycastHit2D hit = Physics2D.GetRayIntersection( ray );
    
                if(hit.collider != null) {
                     Debug.Log("I hit: "+hit.gameObject.tag);
                    //And here you can check what GameObject was hit
    
                    if(hit.gameObject.tag == "AnyTag"){
                         //Here you can do whatever you need for AnyTag objects
                    }
                }
            }   
    
            clickTimer = 2f;
        }
    }