Advertisement
connektiv8

Context menu for Chat system

Jan 28th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. [System.Serializable]
  8. public class ContextMenuItem
  9. {
  10.     // this class - just a box to some data
  11.  
  12.     public string text;             // text to display on button
  13.     public Button button;           // sample button prefab
  14.     public Action<Image> action;    // delegate to method that needs to be executed when button is clicked
  15.  
  16.     public ContextMenuItem(string text, Button button, Action<Image> action)
  17.     {
  18.         this.text = text;
  19.         this.button = button;
  20.         this.action = action;
  21.     }
  22. }
  23.  
  24. public class ContextMenu : MonoBehaviour
  25. {
  26.     public Image contentPanel;              // content panel prefab
  27.     public Canvas canvas;                   // link to main canvas, where will be Context Menu
  28.  
  29.     private static ContextMenu instance;    // some kind of singleton here
  30.  
  31.     public static ContextMenu Instance
  32.     {
  33.         get
  34.         {
  35.             if (instance == null)
  36.             {
  37.                 instance = FindObjectOfType(typeof(ContextMenu)) as ContextMenu;
  38.                 if (instance == null)
  39.                 {
  40.                     instance = new ContextMenu();
  41.                 }
  42.             }
  43.             return instance;
  44.         }
  45.     }
  46.  
  47.     public void CreateContextMenu(List<ContextMenuItem> items, Vector2 position)
  48.     {
  49.         // here we are creating and displaying Context Menu
  50.  
  51.         Image panel = Instantiate(contentPanel, new Vector3(position.x, position.y, 0), Quaternion.identity) as Image;
  52.         panel.transform.SetParent(canvas.transform);
  53.         panel.transform.SetAsLastSibling();
  54.         panel.rectTransform.anchoredPosition = position;
  55.  
  56.         foreach (var item in items)
  57.         {
  58.             ContextMenuItem tempReference = item;
  59.             Button button = Instantiate(item.button) as Button;
  60.             Text buttonText = button.GetComponentInChildren(typeof(Text)) as Text;
  61.             buttonText.text = item.text;
  62.             button.onClick.AddListener(delegate { tempReference.action(panel); });
  63.             button.transform.SetParent(panel.transform);
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement