Dota 2 time based coding

Dota 2 time based coding

Dota 2 time based coding

Dota 2 Workshop Tools/Scripting/Listening to game events

This is a tutorial for beginners. If you see something that can be improved, please improve it!

Contents

Introduction

This tutorial is about the API function ListenToGameEvent . If you call ListenToGameEvent with an event name and a function, the game will call that function every time the event happens.

Example 1

Every time a player levels up, we show a message to all players:

We have two functions here:

  • LevelUpMessage : Here we use the API function Say to show a message to all players.
  • Activate : The game calls this function when it loads the addon. We want the game to call LevelUpMessage every time a player levels up. To do this we call the API function ListenToGameEvent with “dota_player_gained_level” and LevelUpMessage as arguments.

Example 2

When a player reaches level 6, we show a message to all players:

Note: In Level6Message we use the argument, eventInfo , to get the level that the player has reached.

The function ListenToGameEvent

Here is the signature of ListenToGameEvent :

Parameters

Event details

By calling ListenToGameEvent with an event name and a function, you tell the game to call that function every time the event happens. When the game calls the function, it passes a table as an argument to it. This table contains details of the event. On the page Built-In Engine Events you can see which keys the table has. For example, on this page you can see that the table for “dota_player_gained_level” has a key called level (cf. Example 2 above).

Warning: Because Valve sometimes change the events, the list Built-In Engine Events is not always accurate. You can use the pairs function to see which keys a table has:

(Replace tbl with the table you want to inspect.)

Your listener function

If your function is defined like this:

But what if your function is defined like this?

Remember: This is a short way of writing

So your function actually takes two arguments. In this situation, call ListenToGameEvent like this:

or like this (see the FAQ below):

Replace ? with the object that you want to use as self in your function. Here is an example:

Example 3

When an NPC spawns, we print the total number of times this has happened:

More examples

Example 4

When a player picks a hero, we give that hero a blink dagger:

Example 5

The team that first gets 5 hero kills wins:

Example 6

When a unit is killed, it drops a healing salve ( item_flask ):

Question: What does Dynamic_Wrap do?

Answer: Use Dynamic_Wrap if you want the console command “script_reload” to also reload your listeners.

Here are some more details: Suppose you have registered a listener like this:

Dota 2 time based coding

Leave a comment

Design a site like this with WordPress.com
Get started