top of page

An Interpreter in Unity: Introduction

  • Writer: Sam Lench
    Sam Lench
  • 14 hours ago
  • 2 min read

In Unity usually it's the game developer that is writing the code, but what happens if we want to make a game like The Farmer Was Replaced where the player will be the one coding? This is where an interpreter is used. This blog series will focus on creating a basic coding language, and not incorporating a fully featured language such as C# into a video game.


What is an Interpreter?

An interpreter is a program that reads and executes code line by line at runtime, rather than first compiling the program into machine code.


Using an interpreter allows us to design a custom programming language inside a game, like what is shown in the GIF above. The player writes code in this language, and the game processes them and executes them while the game is running.


How it Works

  1. The Lexer (Tokenisation) - This takes the raw text and breaks it into tokens. For example, "Move(North);" Gets turned into "Move", "(","North", ")",";" Each piece here is called a token. Each token represents a meaningful part of the language, such as keywords, symbols or identifiers. White space or comments do not get turned into tokens.

  2. The Parser - This takes the tokens and organises them into a structure called an Abstract Syntax Tree (AST). This makes sure that the code is syntactically correct.

  3. The Interpreter - This walks through the AST created by the parser and preforms the actions described be each node of the tree. For example, our Move(North); code might get turned into transform.Translate(0, 0, 1);

Move(North); //player written code
transform.Translate(0, 0, 1); //code ran by the interpreter

In this example, I have mapped the fictional Move function to the Unity transform.Translate function. So in game, when the player types Move, they are triggering translate.Translate.


What's Coming Next?

In future posts, I'll look at tokenisation, the first stage of interpreting a language.

bottom of page