Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Listening to actions and passing parameters

I’m using Unity 2020.3.17f1, and I am working on a quest system. I want any script to be able to trigger an event, that the quest system will listen to and forward the quest progress based on that.

I am currently using System.Action trying to achieve this, but I need to pass parameters. For example, when I trigger the event OnEnemyKill, I want the listener to be able to know which enemy was killed.

Here is what I have set up so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

QuestActions.cs

using System;

public class QuestActions
{
    public static Action<string> OnEnemyKilled;

}

SpacebarPresser.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpacebarPresser : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            QuestActions.OnEnemyKilled("hello");
        }
    }
}

QuestTracker.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class QuestTracker : MonoBehaviour
{
    private void OnEnable()
    {
        QuestActions.OnEnemyKilled += EnemyKilled;
    }
    
    private void OnDisable()
    {
        QuestActions.OnEnemyKilled -= EnemyKilled;
    }

    private void EnemyKilled(string msg)
    {
        Debug.Log("Message");
    }


}

The problem with my code, is that in QuestTracker.cs, I can’t figure out how to get the parameter that was used when invoking the action in SpacebarPresser.cs.

I have tried using other event-set-ups, but ran into the same problem when using delegates and events, and scriptable object events.

>Solution :

The value you’re passing as a parameter when you invoke OnEnemyKilled should just be coming through as the msg parameter in EnemyKilled.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading