Don't know how to access UnityEvent listener
Hi! I don't know a lot about coding but for a project i'm working on I have to create some c# scripts. I'm using UnityEvent listener on a empty gameobject with a collider to trigger some animations and other simple things.
What i'm trying to do is to access all gameobjects I added in the UnityEvent listener via the inspector to do something like SetActive(false) and when the player collide SetActive(true) before the invoke(). The problem is: I don't know how to access those objects.
Normaly I know how to do it with a simple GameObject variable but I can't figure it out with the event listener.
Thanks for the help!
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(Collider))]
public class EventTrigger : MonoBehaviour
{
#region Attributes
[SerializeField]
private bool disableOnStart;
[SerializeField]
private UnityEvent __onTriggerEnter = null;
#endregion
void Start()
{
if(disableOnStart == true)
{
//I want to disable all gameObjects added to the script with the UnityEvent (something like gameobject.SetActive(false))
}
}
private void OnTriggerEnter(Collider PCol)
{
if (PCol.tag == "PlayerMotor")
{
//I want to enable all gameObjects before the Invoke()
__onTriggerEnter.Invoke();
}
}
}
Answer by Hellium · May 14, 2020 at 02:09 PM
void Start()
{
if(disableOnStart)
{
int targetsCount = __onTriggerEnter.GetPersistentEventCount();
for (int i = 0 ; i < targetsCount ; ++i)
{
if (__onTriggerEnter.GetPersistentTarget(i) is GameObject go)
go.SetActive(false);
}
}
}
private void OnTriggerEnter(Collider PCol)
{
if (PCol.tag == "PlayerMotor")
{
if(disableOnStart)
{
int targetsCount = __onTriggerEnter.GetPersistentEventCount();
for (int i = 0 ; i < targetsCount ; ++i)
{
if (__onTriggerEnter.GetPersistentTarget(i) is GameObject go)
go.SetActive(true);
}
}
__onTriggerEnter.Invoke();
}
}
Wow that was quick! It works like a charm! thanks a lot for your help!
Your answer
Follow this Question
Related Questions
arrow from text to object - complete beginner 0 Answers
Question about triggering an event (Extremely Novice to Programming) 1 Answer
Problems with respawning using a very simple script 1 Answer
How to add a editing option to variables in a script in Inspector? 0 Answers
How to make a random object generator that responds to simple touch? 0 Answers