[C #] I can't trigger a local event

I can trigger my event from lua or js but cannot trigger it from C #. So I would like to know what is my mistake?

using System;
using CitizenFX.Core;
using static CitizenFX.Core.Native.API;

namespace Vanilla
{
    public class Client : BaseScript
    {
        public Client()
        {
            EventHandlers["eventName"] += new Action<string>(TargetFunction);
            TriggerEvent("eventName", "Hello World!");
        }

        private void TargetFunction(string param)
        {
            Debug.WriteLine(param);
        }
    }
}

It may be because TriggerEvent() cannot be called in the constructor. Try calling it in the onClientResourceStart event instead.
Also I highly recommend using Attributes for event handlers, ticks and commands.

Basically, try this:

using System;
using CitizenFX.Core;
using static CitizenFX.Core.Native.API;

namespace Vanilla
{
    public class Client : BaseScript
    {
        [EventHandler("onClientResourceStart")]
        private void OnClientResourceStart(string resourceName)
        {
            if (resourceName != GetCurrentResourceName())
                return;

            TriggerEvent("eventName", "Hello World!");
        }

        [EventHandler("eventName")]
        private void TargetFunction(string param)
        {
            Debug.WriteLine(param);
        }
    }
}
1 Like

You should be able to call BaseScript.TriggerEvent within the constructor however, in this instance, the event may not actually be registered to the resource at that time? Not sure really as I would just call TargetFunction directly from the constructor in that scenario anyway because it’s a lot more efficient…

Can you call events registered in other resources (which have been started prior to this resource) within the constructor?

1 Like

Thanks for your solution but I ended up calling TargetFunction directly in the constructor which was the same thing and was much easier to do.

I don’t know why I would absolutely want to trigger an event because indeed I can directly call TargetFunction :sweat_smile:, so I opt for this solution instead. And yes I can trigger events registered in other resources started before.

Thanks for the help

1 Like