0

I have a scenario where multiple gameObjects are doing something very similar. onTrigger, a gameObject calls a function in a controller. (The destination function is different for each gameObject, but one gameObject always calls that one function)

This seems like a lot of duplicate code to me and I'd like to abstract the functionality; very similar to how the button OnClick() handles this case:

Button OnClick()

I naturally thought that was a good place to start and dug around the docs and forums and cobbled together something. Currently, my code is at:

using UnityEngine; 
using UnityEngine.Events;

/**
 * This script takes in a callback function, and a gameObject tag.
 * When OnEnterTrigger2D is executed, calls the call back function if the collision tag matches given tag
 *
 * Use it for reccuring events in multiple gameObjects like spawning obstacles when it hits spawn points,
 * or to call Endgame when player hits obstacles
 */

public class OnTriggerEnterCallFn : MonoBehaviour
{
    public string targetTag;
    public EventTrigger.TriggerEvent callbackFn;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag(targetTag))
        {
            callbackFn.Invoke(null);
        }
    }
}

Thought that was all that was reasobable needed, but I seem to be missing something because, in the Unity UI, when I assign the class, my function is not visible at all:

enter image description here

My FlappyBirdObstacleManager has the function definition as public void CreateNewObstacle() and even making that public void CreateNewObstacle(BaseEventData ed) didn't have a positive effect.

What am I missing please?

0

2 Answers 2

2

You seem to not really require the BaseEventData parameter since you are passing in null anyway. I think you should rather simply use a parameterless UnityEvents instead.

public UnityEvent callbackFn;
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that worked, thanks so much, I can't believe I've been searching around about 30 minutes now and didn't look into UnityEvent
0

Example implementation of Unity script with UnityEvent

using UnityEngine;
using UnityEngine.Events; // Make sure to import UnityEvent explicitly

public class DrawingState : MonoBehaviour
{
    [System.Serializable]
    public class CallbackEvent : UnityEvent{}

    public CallbackEvent callbackFn;

    void Start()
    {
        if (callbackFn != null)
        {
            callbackFn.Invoke();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.