Skip to content

Instantly share code, notes, and snippets.

@aesthezel
Last active January 24, 2021 14:33
Show Gist options
  • Save aesthezel/271b5a8ddf7e3ba3a196efb1a5e77fec to your computer and use it in GitHub Desktop.
Save aesthezel/271b5a8ddf7e3ba3a196efb1a5e77fec to your computer and use it in GitHub Desktop.
A event and delegate button with OnClick via code on Unity
using UnityEngine.UI;
public class ButtonAction
{
public delegate void PutAction(ButtonAction button, string condition);
public event PutAction Actioned;
private string state;
private Button button;
private int amount;
public void BroadcastAction()
{
if(Actioned != null)
{
//Debug.Log($"[ButtonAction] Button generated with the state of {name} with the quantity of {amount}");
Actioned(this, name);
}
}
}
using UnityEngine;
public class ButtonManager : MonoBehaviour
{
[SerializeField] private ButtonAction[] buttons = new ButtonAction[1];
[SerializeField] private string targetTag = "Selectable";
private GameObject target;
public void AddAction(ButtonAction btn, string condition)
{
if (target != null)
{
switch (condition)
{
case "Heal":
target.DoSomething1(btn.amount);
break;
case "Damage":
target.DoSomething2(btn.amount);
break;
case null:
break;
}
}
}
void Start()
{
foreach(ButtonAction btn in buttons)
{
btn.Actioned += AddAction;
btn.button.onClick.AddListener(() => btn.BroadcastAction());
}
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
var mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(mouseRay, out var rayHit))
{
var select = rayHit.transform;
if(select.CompareTag(targetTag))
{
target = rayHit.collider.GetComponent<IInteractible>();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment