I am making an interaction system for a TPS game and am currently trying to make a Splinter Cell-like interaction system where you can choose what you're going to interact with in a pop-up menu.
I figured out a way to create the list of interactables and get an UI set up, but I don't know how to assign the interaction of the specific items (which have an interface for interacting with an empty Interact function) to a click of the button.
I am guessing events is the way to go, but I don't know how to assign the script to the button onClicked event by instantiating it.
`
private void Update()
{
interactorsFound = Physics.OverlapBoxNonAlloc(interactor.position, GetComponent<BoxCollider>().size, collidersFound, Quaternion.identity, interactablesLayer, QueryTriggerInteraction.Ignore);
if (interactorsFound != 0)
{
interactionUI.SetActive(true);
interactionInteractButton.SetActive(true);
for (int i = 0; i < interactorsFound; i )
{
var _interactorsFound = collidersFound[i];
if (_interactorsFound.GetComponent<IInteract>() != null)
{
if (!interactablesList.Contains(_interactorsFound.gameObject))
{
interactablesList.Add(_interactorsFound.gameObject);
foreach (GameObject item in interactablesList)
{
if (interactionBackground.transform.childCount > 0)
{
for (int k = 0; k < interactionBackground.transform.childCount; k )
{
Destroy(interactionBackground.transform.GetChild(k).gameObject);
}
}
StartCoroutine(DeleteRoutine(interactionBackground));
}
}
}
}
}
// if interactorsFound == 0
else
{
for (int i = 0; i < interactionBackground.transform.childCount; i )
{
Destroy(interactionBackground.transform.GetChild(i).gameObject);
}
interactablesList.Clear();
interactionUI.SetActive(false);
interactionInteractButton.SetActive(false);
}
}
private IEnumerator DeleteRoutine(GameObject gameObject)
{
yield return new WaitUntil(() => gameObject.transform.childCount == 0);
for (int j = 0; j < interactablesList.Count; j )
{
Instantiate(interactionOption, interactionUI.transform.position, quaternion.identity, interactionBackground.transform);
interactionBackground.transform.GetChild(j).GetComponentInChildren<TMP_Text>().text = interactablesList[j].name;
interactionBackground.transform.GetChild(j).name = interactablesList[j].name;
}
}
`
CodePudding user response:
Initiate Button
You can initiate a button prefab or pre-existing game object with button component.
Add Onclick Event Listener to it
Use GetComponent() method to get the button component. Then use button.Onclick.AddListener(YourButtonClickMethod) to add the button-clicked method you want.
You can get the code example from the link below (the onClick part) : https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.UI.Button.html