So, Mike Hunt, your question is so interested me, I decided to implement a full solution. After three hours of trying different things, I ended up with this step-by-step solution:
(pleasePlease note, that this IS NOT very good code, so I will accept any editionsedits)
(thisThis panel will be a container for our context-menu buttons)
(atAt this point our Panel will shrink down to a line. It's normal. This panel will accept buttons as childschildren, align them vertically and stretch to summary content height)
(thisThis button will be instantiated and customized to show context-menu items)
(thisThis script has a method that creates and shows Context Menu)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public class ContextMenuItem
{
// this class - just a box to some data
public string text; // text to display on button
public Button button; // sample button prefab
public Action<Image> action; // delegate to method, that needneeds to be executed when button is clicked
public ContextMenuItem(string text, Button button, Action<Image> action)
{
this.text = text;
this.button = button;
this.action = action;
}
}
public class ContextMenu : MonoBehaviour
{
public Image contentPanel; // content panel prefab
public Canvas canvas; // link to main canvas, where will be Context Menu
private static ContextMenu instance; // some kind of singletonesingleton here
public static ContextMenu Instance
{
get
{
if(instance == null)
{
instance = FindObjectOfType(typeof(ContextMenu)) as ContextMenu;
if(instance == null)
{
instance = new ContextMenu();
}
}
return instance;
}
}
public void CreateContextMenu(List<ContextMenuItem> items, Vector2 position)
{
// here we are creating and displaying Context Menu
Image panel = Instantiate(contentPanel, new Vector3(position.x, position.y, 0), Quaternion.identity) as Image;
panel.transform.SetParent(canvas.transform);
panel.transform.SetAsLastSibling();
panel.rectTransform.anchoredPosition = position;
foreach(var item in items)
{
ContextMenuItem tempReference = item;
Button button = Instantiate(item.button) as Button;
Text buttonText = button.GetComponentInChildren(typeof(Text)) as Text;
buttonText.text = item.text;
button.onClick.AddListener(delegate { tempReference.action(panel); });
button.transform.SetParent(panel.transform);
}
}
}
Now, try to run it. When you right-clicking object, context menu should appear, populated with list that we made. Pressing buttons will print into console some text, and context menu will be destroyed.
PNow, try to run it.S When you're right-clicking the object, the context menu should appear, populated with list that we made. sorry for my EnglishPressing buttons will print into the console some text, and the context menu will be destroyed.
(I don't know is it allowed to post links like that, so dear Moderator, delete it if you wish)