[C#] What does Tick mean?

So i have recently started coding in c# but i don’t really get what this does

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CitizenFX.Core;
using CitizenFX.Core.UI;
using CitizenFX.Core.Native;

namespace testing.Client
{
    public class ClientScript : BaseScript
    {
        public ClientScript()
        {
            Tick += OnTick;
        }


        private async Task OnTick()
        {

        }

    }
}

And how is the Tick used? can it be used on the client and on the server side?

I have been coding much on Lua, and does it work as a thread?

Thanks

1 Like

Yes

Just like you just showed. You add a Task to the Tick event dictionary (I think it’s a dictionary).

It’s pretty much like a while true do loop in Lua. A Tick runs every single “tick” of the server or client (depending where it resides).

Everything you do in C# runs on a thread afaik, but like I said, a Tick can be seen as a continuous loop

1 Like

Is it nessasary to be used?

You should only use a Tick if you want to do something every tick, like checking whether the player is a certain distance away or drawing a marker on the ground. It’s the same as in Lua where you’d put stuff in a while true loop.

You can have a class without any tick and just have events, which would be .

EventHandlers.Add("someName", new Action<string>(OnSomeName)); // in the constructor

private void OnSomeName(string myName)
{
    Debug.WriteLine(name);
}
2 Likes

ok thanks

so it works like a tread in Lua

Citizen.CreateThread(function()
    while true do
     --stuff here
    end
end)

That’s the Lua equivalent of a tick, yes

2 Likes

But, are you able to add something like a wait in Lua to a tick or not?

Yes.

Since a Tick is async, you can use:

await Delay(1000); to block this for 1 second.

Delay(); is from the BaseScript class

4 Likes

Great help :slight_smile:

Tick is a standard .NET event which is an implementation of the observer pattern.

protected event Func<Task> Tick

You subscribe handlers to the trigger of the event. The observer pattern allows subscription of multiple Observers to a Publisher. So Tick is the Publisher in this case and you can subscribe as many Observers as you like (event handlers).

Tick += DisplaySomeMessage;
Tick += HandleSomeKeyPress;

When the events triggers (Publishes) each subscribed observer is called in an undetermined order asynchronously, so a thread is created for each at the time it triggers. Really efficient compared with the Lua counterpart.

No that’s not correct. That while loop is NOT synchronised with the CitizenFX game loop frame tick. For that you need Citizen.Wait(0) inside the loop.