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:
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.