October 19, 2026
Artificial intelligence system for non-player characters using Behavior Trees in Unreal Engine
Artificial Intelligence System for Non-Player Characters Using Behavior Trees in Unreal Engine
Suzana Lopes de Azevedo; Diego Marques de Carvalho
DOI: 10.22167/2675-6528-202603470
Article derived from a Course Conclusion Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
A basic artificial intelligence system for non-player characters (NPCs) was developed and analyzed, using behavior trees in the Unreal Engine. Its adherence to software engineering best practices was evaluated, compared to the finite state machine, a technique traditionally used for behavior control in games. The objective was to develop and analyze an artificial intelligence (AI) for NPCs in the Unreal Engine, employing Behavior Trees, and to evaluate its adherence to software engineering best practices in comparison with finite state machines. The applied quantitative methodology involved the survey of functional and non-functional requirements, the modeling of patrol and pursuit behaviors, and the creation of a functional prototype in Unreal Engine 5.7.4. Performance tests were conducted and a comparative evaluation of software engineering best practices between the approaches was performed. Functionality tests indicated that both approaches were effective. In terms of computational performance, the Behavior Tree demonstrated greater fluidity (FPS) and lower resource consumption (frame time, GPU, and memory) in most scenarios, as well as greater stability. In the evaluation of software engineering best practices, the Behavior Tree stood out in modularity, scalability, and organization, while the finite state machine presented a better average initial detection time. It was concluded that it is feasible to create AI for NPCs with software engineering best practices in the Unreal Engine. The Behavior Tree offered a more modular, flexible, and scalable architecture, aligned with software engineering principles, although the choice of the ideal technique depends on the specific project context and objectives.
Keywords: Autonomous agents; Software engineering; Digital games; Finite state machines.
1. Introduction
Non-Playable Characters (NPCs), or non-playable characters, represent crucial elements in digital games. Controlled by the computer, these characters act as enemies, allies, or extras, performing everyday activities and reacting to the environment autonomously. This autonomy is fundamental to creating an immersive, interactive, and challenging gaming experience for the player (Rogers, 2013).
For NPCs to function autonomously and reactively, the development of an effective artificial intelligence (AI) system is essential. Creating a good AI requires aligning game requirements with desired behaviors and selecting the appropriate algorithm for its implementation (Millington, 2019). In this context, the demand arises for approaches that allow structuring AI in a professional manner and aligned with software engineering best practices.
In the realm of game development, Unreal Engine stands out as free and accessible software, offering robust features for creating AI for non-player characters. Among its tools, Behavior Trees (BT) allow for organizing behavioral logic in a branched flow, utilizing a “Blackboard” to store and manage decision-making data (Epic Games, 2025). In parallel, the Finite State Machine (FSM) is another widely used technique for AI, controlling the NPC through states and transitions based on conditionals (Bourg and Seemann, 2004).
Despite the popularity of both techniques, the choice of the most suitable development approach for AI in NPCs, especially regarding adherence to software engineering principles, remains a relevant research point. There is a need to demonstrate how the use of tools like Behavior Trees can optimize structural organization, maintainability, and scalability in NPC development, compared to simpler implementations based on finite state machines.
This work is justified by the relevance of exploring and comparing these approaches, aiming to provide subsidies for the development of artificial intelligence in digital games that are efficient and aligned with software engineering principles. Thus, this work aims to develop and analyze an AI for NPCs in the Unreal Engine through the Behavior Trees system, evaluating its application and its adherence to good software engineering practices.
2. Material and Methods
This research was characterized as applied, quantitative, and exploratory in nature, with the objective of developing and evaluating approaches for implementing artificial intelligence in non-player characters (NPCs) in the Unreal Engine. Applied research focused on solving real problems, using theoretical knowledge for the development of practical solutions (Andrade, 2012). The methodology was structured in sequential steps to ensure the comprehensiveness of the study.
Initially, a literature mapping was performed to identify works related to behavior trees, finite state machines, artificial intelligence, Unreal Engine, and Behavior Trees. The research included classic books such as “Level Up: Un Guia Para O Design De Grandes Jogos” (Rogers, 2013), “AI for Games” (Millington, 2019), and “Engenharia de Software: Uma Abordagem Profissional” (Pressman, 2016), as well as scientific articles on Google Scholar and IEEE Xplore.
The key terms used in the search were “unreal engine”, “NPC”, “Behavior Trees”, “NPC and Unreal Engine”, “Behavior Trees Unreal Engine”, “finite state machine” and “FSM”. As inclusion criteria, recent publications of articles, less than five years old, and relevant and consolidated books in the areas of software engineering and digital game development were considered.
The requirements gathering and analysis stage involved identifying the expected behaviors for an NPC in a basic game. It was decided to restrict the implementation to patrol and chase behaviors, considered sufficient to validate the decision-making models within the available project time.
The functional requirements defined the actions that the NPC should execute: patrol the environment, detect the player through the perception system, initiate a chase upon detecting the player, and return to patrol if the target was lost. The non-functional requirements focused on the quality and organization of the solution, including the implementation of AI with Behavior Trees, adherence to good practices of modularity and low coupling, ease of maintenance and system extension, and utilization of Unreal Engine’s NavMesh for navigation.
The AI modeling of the NPC sought to simulate a simple and functional behavior, capable of dynamically interacting with the player. The NPC’s operating logic was defined through an activity diagram, which represented the main states of patrol and pursuit, serving as the basis for the transitions between behaviors.
The AI’s operational flow was designed for the NPC to initiate a patrol, moving across the map via the NavMesh. During the patrol, the perception system monitored for the player’s presence. Upon detecting the player, a variable in the Blackboard was updated, causing the behavior tree to execute the chase branch. If the player was no longer detected, the variable was updated again, and the NPC returned to patrol behavior.
For the implementation, good software engineering practices were adopted, such as the separation of responsibilities between tasks and services of the Behavior Tree, the use of parameterizable variables in the Blackboard, and low coupling between components. The AI was implemented using native resources of Unreal Engine 5.7.4, through the visual scripting system Blueprint, without the use of C++ code.
The components used included the Blueprint AI Controller, responsible for controlling NPC actions; the Behavior Tree, for organizing decision-making; the Blackboard, for storing and managing relevant data; AI Perception, which simulated the NPC’s sense of vision; and the NavMesh, to enable efficient NPC navigation in the environment. A UML class diagram was created to highlight the structure and relationships between these components.
The functional prototype was developed in Unreal Engine 5.7.4 in a computational environment with hardware specifications that included a B550M DS3H AC motherboard, an AMD Ryzen 5 5500 processor, an NVIDIA GeForce RTX 3050 6 GB GDDR6 graphics card, 16 GB of RAM, and 512 GB M.2 2280 NVMe PCIe Gen4x4 SSD storage. The operating system used was Windows 11 Pro 64-bit, version 25H2, with DirectX 12 support, and the development environment included Visual Studio Community 2022.
For the prototype construction, free assets from the creator Kenney were used, from the Animated Characters Survivors and Retro packages, to create three distinct characters. One character represented the player, with animations and commands for locomotion, crouching, jumping, and attacking. The other two characters were NPCs, one controlled by Behavior Tree and the other by a finite state machine, both with the AI Perception component configured with the same parameters for player detection.
The prototype scenario was a simple level, built with standard geometric objects from the Unreal Engine to simulate obstacles and allow character navigation. A NavMesh Bounds Volume was inserted to configure NavMesh-based navigation. Tests were performed on a monitor with a resolution of 1920 x 1080 pixels, using the Play in Viewport of the Unreal Engine editor.
The tests were defined for a comparative analysis of the implemented approaches, evaluating NPC behavior, application performance, and solution quality. Metrics included player detection efficiency (average time to find the player), detection success rate (ability to detect the player within 30 seconds), and chase effectiveness (capture success rate).
Computational performance was measured in terms of frames per second (FPS), frame time in milliseconds (ms), Graphics Processing Unit (GPU) rendering time in ms, and memory usage, for scenarios with one, five, and ten NPCs simultaneously. Software engineering best practices were evaluated by objective criteria such as modularity, modifiability, scalability, reusability, and code organization, with measurable indicators for comparison between implementations.
Ten executions for each experimental condition were performed to observe the variability of the results and allow comparison between implementations. Data collection was automated by Unreal Engine, through Blueprint timing and automatically generated logs. For performance data, manual screen capture was performed at sixty seconds of execution, discarding earlier or later captures.
As support for development, artificial intelligence-based tools such as ChatGPT, Claude, and the Epic Developer Assistant for Unreal Engine were used to assist in clarifying doubts and reviewing text. Technical tutorials and official materials from Unreal Engine and YouTube were also consulted as practical support during implementation.
3. Results and Discussion
The bibliographic survey conducted in the present study provided an in-depth understanding of artificial intelligence techniques applied to digital games, allowing the identification of the characteristics, advantages, and limitations of approaches based on behavior trees and finite state machines. This stage was crucial for contextualizing the research and grounding the comparative analysis of the developed implementations, aligning with the principles established by Millington (2019) on the creation of effective AI.
The Artificial Intelligence Used in Games
Game developers seek to build artificial intelligence algorithms that lend realism to characters, mimicking human behaviors and applying the most suitable tools to character design. It is a common mistake to assume that a more complex AI will result in a superior character; in fact, a simple, well-executed AI can be perceived as more intelligent by the player (Millington, 2019). The key lies in aligning the game’s requirements with the desired behaviors and the appropriate algorithm for their production.
The finite state machine (FSM) is an abstract model that assumes distinct and predefined states, with conditions that determine the transitions between them. Although it is an old technique, its simplicity of understanding, implementation, and debugging keeps it relevant in modern games. Generally, the FSM stores all the data of an entity in a single class or structure, which defines the current state of the AI and, consequently, its behavior (Bourg and Seemann, 2004).
The basic structure of the FSM is quite flexible, allowing for various implementations. In its most elementary form, the algorithm requires little memory, only to store the current state and process the corresponding transactions (Millington, 2019). This characteristic contributes to its popularity in scenarios where simplicity and speed of implementation are priorities, despite its limitations in more complex contexts.
The behavior tree (BT) architecture has gained popularity in creating artificial intelligence for characters, being used in games like Halo 2, released in 2004, and subsequently adopted by many other titles (Millington, 2019). The main component of a behavior tree is the task, which can range from reading a variable to a complex animation, organizing behavioral logic hierarchically and modularly.
According to Millington (2019), simple tasks in a BT are classified into three types: conditions, which test game properties and return success or failure; actions, which alter states, control animations, audio, and movement; and compositions, which decide the order and execution of tasks, such as “Selector” and “Sequence”. Selectors choose the first successful action, while sequences ensure the execution of a series of necessary tasks, allowing the creation of sophisticated behaviors.
The behavior tree adopts a form of reactive planning, requiring all possible NPC actions to be added manually. To avoid predictability and make the AI more interesting, it is possible to incorporate variations in selectors and sequences, allowing children to be executed in random order (Millington, 2019). This flexibility is an important differentiator for creating more dynamic and less repetitive gaming experiences.
NPC Performance and Efficiency
The first test evaluated the player detection efficiency, measuring the time between the start of the NPC’s patrol and the player’s identification by the perception system. The finite state machine (NPC FSM) based model showed an average detection time of 29 seconds, with a standard deviation of 35.9 seconds. In contrast, the behavior tree (NPC BT) based model recorded an average of 46.1 seconds, with a standard deviation of 35.6 seconds. Although the NPC FSM was faster in initial detection, both models exhibited high variability, suggesting that the random choice of patrol points significantly influenced the detection time.
The high dispersion in the results, with similar standard deviations for both models, indicates that the agents’ behavior varied considerably between runs, not establishing a uniform performance pattern. Navigation in Unreal Engine, which uses the NavMesh system for route calculation and navigation mesh processing, can impact both computational cost and trajectory complexity (Zhang, 2025). Despite the differences, both models fulfilled the objective of detecting the player and initiating the chase.
The second test, focused on the player detection success rate within 30 seconds, reinforced the trend observed in the first test. The FSM NPC achieved an 80% success rate, while the BT NPC obtained 40%. This result is consistent with the lower average detection time of the FSM NPC, indicating that, in the evaluated scenario, the finite state machine decision logic favored the player’s location within the established time limit. However, it is crucial to emphasize that these results are specific to the scenario and implementation of this work, not allowing generalizations to all contexts.
The third test evaluated the effectiveness of the chase behavior, considering the NPC’s ability to reach the player. The BT NPC demonstrated superior performance, with an average success rate of 57% and a standard deviation of 19.9%, compared to the FSM NPC, which achieved 22.8% success and a standard deviation of 22.17%. The BT NPC also presented an average of 2.7 reaches per execution, versus 0.7 for the FSM NPC, evidencing greater effectiveness in completing the chase.
Regarding execution escapes, both models presented similar averages, with the NPC BT registering 2.3 escapes and the NPC FSM, 2.2 escapes. Although the NPC FSM exhibited a slightly lower standard deviation in escapes, the close averages indicate that both models generated a similar amount of escape events. This complementarity of performance, where the NPC FSM stood out in initial detection and the NPC BT in pursuit, suggests that the choice of the ideal architecture depends on the specific task to be executed.
The exclusive use of behavior trees may present limitations in responding to specific external events, as pointed out by Millington (2019), who suggests combining BT with state machines or implementing tasks that simulate state-oriented behaviors in such scenarios. This perspective reinforces that the decision between BT and FSM should consider not only quantitative performance but also the type of expected behavior and the level of control required over the agent’s transitions.
In the computational performance test with an active NPC, the behavior tree-based model (BT NPC) demonstrated better performance. The BT NPC achieved an average of 79.3 FPS, an average frame time of 12.57 ms, GPU processing time of 9.39 ms, and memory consumption of 1.69 GB. In contrast, the FSM NPC recorded 65.3 FPS, 14.75 ms per frame, 10.27 ms on the GPU, and 2.39 GB of memory. The BT NPC also showed lower standard deviations across all metrics, indicating greater execution stability.
With five active NPCs, the BT NPC model maintained its superior computational performance, averaging 79.7 FPS, 12.59 ms per frame, 9.06 ms on the GPU, and 1.63 GB of memory. The FSM NPC, in turn, recorded 65.6 FPS, 14.94 ms per frame, 9.36 ms on the GPU, and 2.17 GB of memory. Standard deviations confirmed the greater stability of the BT NPC, with the exception of memory consumption, where the difference was insignificant. These results indicate that the BT NPC maintained a lower computational cost and more stable behavior even with the increase in the number of agents.
In the scenario with ten active NPCs, both models showed a reduction in the average frame rate per second, which is expected due to the increased computational load. Still, the BT NPC maintained an average of 72.6 FPS and an average time per frame of 13.73 ms, while the FSM NPC registered 67.0 FPS and 14.69 ms per frame. In terms of memory consumption, the BT continued to use fewer resources (1.56 GB) than the FSM (2.62 GB), also maintaining lower variability.
However, in the scenario with ten NPCs, the FSM NPC presented a lower average GPU processing time (8.51 ms) and a lower standard deviation in this metric, suggesting that, with a larger number of simultaneous agents, part of the graphical processing associated with the FSM became relatively more efficient. Despite this specific advantage, the overall performance of the BT remained superior in the other analyzed metrics, reinforcing the importance of a multidimensional performance evaluation, which considers not only the number of agents but also specific metrics.
Evaluation of Software Engineering Best Practices
The evaluation of software engineering best practices was carried out through the inspection of implementation artifacts, considering the organization of Blueprints, the distribution of responsibilities, modularity, degree of dependency, reusability potential, and the impact of including new behaviors. The criteria were based on the quality characteristics of ISO/IEC 25010:2023, such as maintainability, reusability, and modifiability, and on Pressman’s (2016) software design principles, which address modularity, separation of responsibilities, cohesion, and coupling.
In terms of modularity, the behavior tree scored maximum, demonstrating greater modularity due to the distribution of its decisions across independent files. This allows for functional isolation and lower coupling between behaviors. Each behavior in the BT occupies its own artifact, resulting in five files with a single responsibility. In the FSM, the logic is concentrated in conditional flows within a single Blueprint, with approximately 21 nodes, which reduces modular flexibility and structural clarity.
Regarding modifiability, both approaches received equivalent scores, as altering existing behaviors or adding new ones requires structural modifications. In BT, including a new behavior requires creating a new task or service and inserting it into the tree. In FSM, it is necessary to include the new state in the Enum and modify the logic in the Blueprint AI Controller. This characteristic aligns with the literature, which points out that “hard-coded” FSMs become difficult to maintain and complex as they grow (Millington, 2019).
The scalability of the behavior tree proved to be a significant advantage, allowing the addition of new behaviors through subtrees without the need for substantial system restructuring. Functional growth occurs by adding or combining components, minimizing changes to existing components. This characteristic is crucial as the quantity and complexity of NPC behaviors increase, aligning with Pressman’s (2016) software engineering principles on modularity and responsibility organization.
In the finite state machine, the inclusion of new behaviors expands the code in the same file, requiring comment blocks to identify each group of nodes and rapidly increasing the complexity of the state graph, impacting the readability of the Blueprint. This conclusion is related to the architecture implemented in this work and does not imply that behavior trees are universally superior in scalability, but highlights the importance of the distribution of responsibilities and the composition mechanisms used in the implementation.
Both approaches presented component reuse capability, receiving equivalent scores. In FSM, the AI Controller allows associating the same implementation to different characters, with variations obtained by parameterization or class specialization. In Behavior Tree, reuse occurs through independent tasks and services, which can be employed in different trees and characters, as described by Millington (2019), allowing the composition and instantiation of behaviors from predefined tasks.
Regarding organization, the behavior tree presented greater structural organization due to the explicit separation between decision-making and execution components. This organization reflects the principle of separation of concerns, where different elements have specific functions. In the analyzed FSM, most of the logic is concentrated in the Blueprint AI Controller, resulting in a more extensive and visually dense graph as new behaviors are incorporated, making it difficult to identify the structure.
The results obtained are aligned with related works, which demonstrate Behavior Tree as a safe and flexible approach for organizing hierarchical structural behaviors in game engines, allowing controlled alternation and extensibility (Ferreira and Kishimoto, 2024). The choice of software architectures directly impacts production costs, as systems with high coupling between components generate higher maintenance costs (MacCormack and Sturtevant, 2016). Reusability, flexibility, and extensibility are recurring requirements in game mechanics architecture, and modular architectures reduce development effort (Mizutani et al., 2021).
In summary, the behavior tree, by distributing responsibilities into independent artifacts and decoupling data via a Blackboard, presents architectural characteristics aligned with best practices that literature associates with reduced maintenance costs and greater long-term system evolution capacity. The finite state machine, in turn, offers simplicity and ease of implementation and debugging, being suitable for simpler scenarios with a limited number of states and transitions (Premoli and Silva, 2024). The choice of the ideal technique, therefore, depends on the specific game objectives and the development context (Valadares and Ribeiro, 2022).
4. Conclusion
This study aimed to develop and analyze an artificial intelligence for non-player characters (NPCs) in the Unreal Engine, employing the Behavior Trees system, and to evaluate its adherence to software engineering best practices compared to finite state machines. It was found that both approaches were effective in implementing patrol and pursuit behaviors. However, a complementary performance was observed: the finite state machine demonstrated faster initial player detection, while the Behavior Tree showed greater effectiveness in completing the pursuit. In terms of computational performance, the Behavior Tree generally exhibited greater fluidity and lower resource consumption, as well as higher stability, although the finite state machine showed a slightly lower GPU processing time in scenarios with a higher number of agents. The analysis of software engineering best practices revealed that the Behavior Tree excelled in modularity, scalability, and organization, offering an architecture more aligned with software engineering principles, with distribution of responsibilities and lower coupling. The main contribution of this work lies in demonstrating the feasibility of creating AI for NPCs with software engineering best practices in the Unreal Engine, providing subsidies for choosing the most suitable architecture according to project objectives.
It should be noted that the tests were conducted in a controlled environment, with a limited number of runs and a simplified scenario, which restricts the generalization of the results to all game development contexts. For future studies, it is suggested to expand the prototype by including additional behaviors, such as attack and receiving damage. It is also recommended to conduct tests in more complex scenarios and with a larger number of runs, in order to broaden the validity of the findings. Additionally, the inclusion of other artificial intelligence models for a more comprehensive comparison can enrich the understanding of the application of these techniques.
Bibliographic References
ANDRADE, M. M. de. 2012. Introdução à metodologia do trabalho científico: elaboração de trabalhos na graduação, 10ª edição. Rio de Janeiro: Atlas. E-book. p.112. ISBN 9788522478392. Disponível em: https://app.minhabiblioteca.com.br/reader/books/ 9788522478392/. Acesso em: 07 fev. 2026.
BOURG, D. M.; SEEMANN, G. 2004. Al for game developers. Beijing; Cambridge: O’reilly
EPIC GAMES. 2025.Unreal Engine 5. Disponível em: <https://www.unrealengine.com/pt-BR/ unreal-engine-5 >. Acesso em: 23 out. 2025.
FERREIRA, J. V. P; KISHIMOTO. 2024 A. Aplicação de Behavior Tree para IA de NPCs inimigos em jogos de survival horror. Trabalho de Conclusão de Curso. Faculdade de Computação e Informática, Universidade Presbiteriana Mackenzie, São Paulo, SP, Brasil. Disponível em: https://dspace.mackenzie.br/items/8ebf626d-9ddc-4ea4-8796-5137c4b334e0 Acesso em: 03 jan. 2026.
INTERNATIONAL ORGANIZATION FOR STANDARDIZATION. 2023. ISO/IEC 25010:2023: Systems and software engineering — Systems and Software Quality Requirements and Evaluation (SQuaRE) Product quality model. Geneva: ISO. Disponível em: https://www.iso.org/standard/78176.html Acesso em: 10 mar 2026
MACCORMACK, A.; STURTEVANT, D. J. 2016. Technical debt and system architecture. In: Journal of Systems and Software. 2016. Boston, Miami, Estados Unidos. v. 120, p. 257–273. Disponível em: https://www.hbs.edu/ris/Publication%20Files/2016-JSS%20Technical%20Debt_d793c712-5160-4aa9-8761-781b444cc75f.pdf Acesso em: 10 mar 2026
MILLINGTON, I. 2019. Artificial Intelligence for Games. 3ed. CRC Press, Reino Unido.
MIZUTANI, W. K.; DAROS, V. K.; KON, F. 2021. Software architecture for digital game mechanics: a systematic literature review. In: Entertainment Computing, v. 38, 100421, 2021. Disponível em: https://doi.org/10.1016/j.entcom.100421. Acesso em: 10 mar 2026
PREMOLI, Breno de Oliveira; SILVA, Victor Amaral. 2024. Estudo sobre o comportamento de npcs e inimigos em jogos digitais utilizando a inteligência artificial. Trabalho de Conclusão de Curso em Tecnólogo em Análise e Desenvolvimento de Sistemas. Faculdade de Tecnologia de Presidente Prudente, Presidente Prudente, SP. Brasil Disponivel em: https://ric.cps.sp.gov.br/handle/123456789/23495. Acesso em: 03 jan. 2026
PRESSMAN, R. S. 2016. Engenharia de Software: Uma Abordagem Profissional. McGraw Hill, Porto Alegre, PR, Brasil.
ROGERS, S. 2013. Level Up Um Guia Para O Design De Grandes Jogos. Blucher, São Paulo, SP, Brasil.
VALADARES, Gabriel Pacini O.; RIBEIRO, Marcos Wagner S.. Técnicas de Inteligência Artificial na Criação de Personagens Não Jogáveis: uma Revisão de Literatura. In: TRILHA DE
ZHANG, J. 2025 Implementation and Research of Artificial Intelligence Characters Based on Unreal Engine 5. Asia-Europe Conference on Cybersecurity, Internet of Things and Soft Computing (CITSC), Rimini, Italy, 2025. p. 73-77. Disponível em: https://ieeexplore.ieee.org/document/10936510. Acesso em: 03 jan. 2026.
Article originating from the Final Course Work of the Specialization in Software Engineering of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform