Skip to main content

Functions

When scripts grow beyond twenty lines, putting everything inside OnTick or OnKeyDown creates an unreadable mess. A function (called a method in C# when attached to a class) lets you name a piece of work, give it parameters, and call it whenever needed.

Anatomy of a method

A method has four key components:

private bool IsPlayerNearTarget(Vector3 targetPosition, float maxDistance)
{
Ped player = Game.Player.Character;
if (player == null || !player.Exists())
{
return false;
}

float distance = player.Position.DistanceTo(targetPosition);
return distance <= maxDistance;
}
  1. Access modifier (private): In a script class, almost all helper methods should be private. Only methods intended to be called from the outside need to be public.
  2. Return type (bool): What the method hands back to whoever called it. If it produces no value, use void.
  3. Name (IsPlayerNearTarget): Use PascalCase and start with a verb describing the action or question.
  4. Parameters ((Vector3 targetPosition, float maxDistance)): The inputs required to do the job.

Void methods: performing an action

When a method carries out an action without returning an answer, its return type is void:

private void ApplySunnyWeather()
{
World.TransitionToWeather(Weather.ExtraSunny, 5.0f);
GTA.UI.Notification.PostTicker("Weather updated to sunny.", false);
}

Now your event handler becomes clean and descriptive:

private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F6)
{
ApplySunnyWeather();
}
}

The single responsibility principle

A method should do one thing and do it well. If you have a method named SpawnCarAndArmPedAndStartMission(), you have combined three separate responsibilities into one tangle. If the ped fails to spawn, the mission logic breaks, and testing each part in isolation becomes impossible.

Break them up:

  • SpawnVehicle(...)
  • EquipBodyguard(...)
  • StartMission(...)

Then coordinate them from a single higher-level method.

Next, we look at keyboard input: capturing player keystrokes and avoiding accidental double activations.