Closing a panel after clicking outside of the panel and its children in Unity

 Create a new C# script in Unity and paste this code into it. Drag and drop this script to the panel you want to close after clicking outside of the panel, and you are good to go.


  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6.  
  7. public class ClickOutsideToClose : MonoBehaviour
  8. {
  9.     void Update()
  10.     {
  11.         if(Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2))
  12.         {
  13.             this.gameObject.SetActive(ClickingSelfOrChild());
  14.         }
  15.     }
  16.     private bool ClickingSelfOrChild()
  17.     {
  18.         RectTransform[] rectTransforms = GetComponentsInChildren<RectTransform>();
  19.         foreach(RectTransform rectTransform in rectTransforms)
  20.         {
  21.             if (EventSystem.current.currentSelectedGameObject == rectTransform.gameObject)
  22.             {
  23.                 return true;
  24.             };
  25.         }
  26.         return false;
  27.     }
  28. }

Comments

Post a Comment

Please feel free to comment. I would love to hear feedback.