How to integrate a Chatbot in Unity to create smart AI NPCs

Eden AI
8 min readFeb 1, 2024

In this tutorial, we will walk you through the process of integrating a chatbot into your Unity game using the Eden AI Unity Plugin for AI-powered conversation with non-player characters (NPCs). This integration will add a new layer of interaction, making your game more engaging and dynamic.

What is Unity?‍

‍Founded in 2004, Unity stands as a prominent gaming company providing a robust game development engine, empowering developers to craft immersive games for diverse platforms, such as mobile devices, consoles, and PCs.

Elevating gameplay is achievable through Unity’s capability to seamlessly integrate artificial intelligence (AI), facilitating intelligent behaviors, decision-making processes, and advanced functionalities in your games or applications.

GitHub Unity Eden AI Plugin

Unity provides various avenues for AI integration. Notably, the Unity Eden AI Plugin seamlessly interfaces with the Eden AI API. This integration streamlines the incorporation of AI features, including AI chatbot functionality, into your Unity applications.

Benefits of using NPC AI Chatbots in Unity

Integrating a non-player character (NPC) AI chatbot into Unity can offer several benefits, enhancing both the development process and the overall gaming experience. Here are some advantages of using a chatbot in Unity:

  1. Interactive Gameplay: Chatbots enable interactive and dynamic conversations between players and non-player characters (NPCs), enhancing the overall gaming experience.
  2. Personalized Player Interaction: Developers can use chatbots to create personalized and adaptive gaming experiences, allowing characters to respond dynamically to player actions and choices.
  3. Realistic NPC Interactions: NPCs with chatbot capabilities can engage in more sophisticated and human-like conversations, responding intelligently to player queries and creating a more immersive gaming environment.
  4. Quest Guidance: Chatbots can guide players through quests by providing spoken or text-based instructions, hints, or clues, offering an additional layer of assistance in navigating game objectives.
  5. Accessibility for Diverse Audiences: Chatbots can be utilized to cater to a diverse global audience by providing assistance, translations, or information, making the gaming experience more accessible for players with varying linguistic backgrounds.
  6. Enhanced Storytelling: Chatbots can contribute to the narrative by providing context, backstory, or additional information, enriching the storytelling aspect of the game.
  7. Procedural Content Generation: Chatbots can dynamically generate dialogues, events, or lore within the game, adding depth and context to the gaming world through procedural content generation.
  8. Adaptive Gameplay Mechanics: Developers can introduce innovative gameplay mechanics by incorporating voice or text-based commands, allowing players to control in-game actions using spoken or written words.
  9. Multi-Modal Gaming Experiences: Chatbots open the door to multi-modal gaming experiences, combining visual elements with spoken or written dialogues. This can be particularly beneficial for players who prefer or require alternative communication methods.
  10. Educational and Instructional Games: In educational or serious games, chatbots can assist in delivering instructional content, quizzes, or interactive learning experiences, making the gameplay educational and engaging.

In summary, incorporating an AI chatbot into Unity adds a layer of interactivity, personalization, and immersion to the gaming experience, contributing to a more dynamic and enjoyable environment for players.

Use cases of Chatbots in Video Games made with Unity

Here are some examples and use cases of chatbots in video games created with Unity:

Dungeon Rushers, a Unity-developed tactical RPG, employs a chat-like interface for in-game communication, enabling players to interact with AI NPCs through text-based conversations. These intelligent NPCs allow players to make decisions that significantly impact the storyline and influence the outcomes of their quests.

Rust: Unity Chat System Mod

In the online survival game Rust, modders have created Unity-based chat systems featuring chatbot functionalities. These chatbots assist players by providing essential information about the game world, facilitating trading, and fostering a more interactive player community.‍

Plague Inc: Evolved

Plague Inc: Evolved, a strategy simulation game developed in Unity, presents an opportunity for implementing chatbots to drive interactive storytelling. By incorporating chatbot-driven characters, players can engage in dynamic conversations that directly influence the progression of their viral outbreak scenarios.‍

Astroneer

Astroneer, a space exploration game created with Unity, has the potential to implement chatbots to enhance player communication with in-game AI entities. This includes conversational interactions with intelligent robotic companions, offering guidance, and sharing information about planetary exploration.‍

Tanks Multiplayer

Unity-based multiplayer games, such as a Tanks Multiplayer game, can leverage chatbots for team coordination and communication. Chatbots may assist players in strategizing, provide updates on enemy movements, and enhance the overall multiplayer experience through intelligent NPC interactions.‍

City Building Simulation

Unity-powered city-building simulations stand to benefit from chatbots simulating civic interactions. Players might engage in text-based conversations with AI-driven citizens, addressing concerns, making decisions, and managing the growth of their virtual cities through interactions with NPC AI chatbots.‍

Mystery Adventure Game

In a Unity-created mystery adventure game, chatbots could serve as interactive companions or detectives, aiding players in solving puzzles, providing clues, and adding depth to the narrative through AI-powered conversation with NPCs.‍

Unity-based Educational Game

Educational games developed in Unity can integrate chatbots to engage players in learning activities. These chatbots may act as virtual tutors, delivering instructional content, quizzes, and interactive learning experiences in a conversational format with intelligent NPCs.‍

2D Platformer with Narrative Choices

A Unity-based 2D platformer featuring a branching narrative could leverage chatbots, allowing players to communicate with in-game characters. Conversations with these AI NPCs might significantly influence the storyline, creating a more personalized gaming experience.

These examples highlight the potential use of chatbots in Unity-created video games to enhance player interactions, storytelling, and gameplay dynamics. Unity’s flexibility empowers developers to implement chatbot features tailored to the unique requirements of their games, providing a more immersive and intelligent gaming experience.

How to integrate NPC AI Chatbot into your video game with Unity

Step 1. Install the Eden AI Unity Plugin

Ensure that you have a Unity project open and ready for integration. If you haven’t installed the Eden AI plugin, follow these steps:

  1. Open your Unity Package Manager
  2. Add package from GitHub

Step 2. Obtain your Eden AI API Key

To get started with the Eden AI API, you need to sign up for an account on the Eden AI platform (receive free credits upon registration!).

Try Ede AI for FREE

Once registered, you will get an API key which you will need to use the Eden AI Unity Plugin. You can set it in your script or add a file auth.json to your user folder (path: ~/.edenai (Linux/Mac) or %USERPROFILE%/.edenai/ (Windows)) as follows:

{ "api_key": "YOUR_EDENAI_API_KEY" }‍

Alternatively, you can pass the API key as a parameter when creating an instance of the EdenAIApi class. If the API key is not provided, it will attempt to read it from the auth.json file in your user folder.‍

Step 3. Integrate NPC AI Chatbot on Unity

Infuse life into your non-player characters (NPCs) by enabling them to express themselves through the incorporation of chatbot functionality. Utilizing the Eden AI plugin, you can effortlessly incorporate a diverse range of AI Chatbot APIs, including OpenAI, Google and Replicate into your Unity project (see the comprehensive list here).

AI Chatbot API on Eden AI

‍This feature enables you to customize the model of the engine and behaviour of the assistant, allowing you to tailor the desired ambiance of your game.

GitHub Link

  1. Open your script file where you want to implement the Chatbot functionality.
  2. Import the required namespaces at the beginning of your script:‍
using EdenAI; using System; using System.Threading.Tasks;

3. Create an instance of the Eden AI API class by passing your API key as a parameter. If the API key is not provided, it will attempt to read it from the auth.json file in your user folder.‍

EdenAIApi edenAI = new EdenAIApi();

4. Implement the function to send a request to the chatbot API:

class Program
{
static async Task Main(string[] args)
{
string provider = "openai";
string text = "Hello, I'm fine and you ?";
ChatMessage chatMessage = new ChatMessage()
{
Role = "assistant",
Message = "Hello, how are you?"
};
List<ChatMessage> previousHistory = new List<ChatMessage> { chatMessage };
EdenAIApi edenAI = new EdenAIApi();
ChatResponse response = await edenAI.SendChatRequest(provider, text, previousHistory: previousHistory);
}
}‍

Note: The chatbot is designed to provide responses in the same language as the incoming message. The language specification is handled automatically without the need for explicit instructions in the request. For instance, if you send a message in French, the chatbot will respond in French.

Step 4: Handle the Chatbot Response

The SendChatRequest function returns a ChatResponse response object.‍

Access the response attributes as needed. For example:

if (response.status == "success") { string replay = response.generated_text; 
previousHistory = response.message; // Handle the chatbot reply in your Unity project }
else { // Handle the case where the chatbot request fails }‍

Step 5: Test and Debug

Run your Unity project and test the chatbot functionality. Monitor the console for any potential errors or exceptions and make adjustments as necessary.‍

Conclusion

Congratulations! Your Unity project is now equipped with a chatbot using the Eden AI plugin. Experiment with optional parameters to fine-tune the chatbot’s behavior and enhance the overall gaming experience for your players.

Feel free to explore additional AI functionalities on Unity offered by Eden AI to further elevate your game development.‍

About Eden AI

Eden AI is the future of AI usage in companies: our app allows you to call multiple AI APIs.

  • Centralized and fully monitored billing
  • Unified API: quick switch between AI models and providers
  • Standardized response format: the JSON output format is the same for all suppliers.
  • The best Artificial Intelligence APIs in the market are available
  • Data protection: Eden AI will not store or use any data.

Create your Account on Eden AI

Originally published at https://www.edenai.co.

--

--