0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

UnityでchatGPTのAPIを使う準備

Posted at

2025.9.11時点の記事です。

Unityプロジェクトの準備

・Unity HUBをインストール
・Unityをインストール(例2022.3.22)(最新版でないほうがトラブル少ないと思う)
・適当にプロジェクトを作る。(URPテンプレでOK)

NugetとOpenAIのインストール

OpenAIいれるのに、Nugetからのほうが簡単らしい。

ここから、NuGetForUnity.4.5.0.unitypackageをダウンロードする。

Unityメニューから、先のファイルを指定してインストールして、

image.png

Nugetメニューが増えることを確認。

Nuget Managerを起動する

image.png

image.png

サンプルコードの準備

chatGPTに5ドル課金し、APIでアクセスするためのkeyを発行する。
手順は省略するが、課金上限は設定しておいた方が良い。
chatGPT plusプランである必要はないらしい。

シンプルなテキストエディタなどでapi_key.txtというファイルを作成し、内容は先のアクセスキーの文字列をコピペしておく。

そのapi_key.txtファイルをUnityのAssets直下に置く。
(アプリとして書き出す場合は、直下ではダメらしい。)

image.png

Assetsフォルダの中で、右クリックメニューから、Create、C# Scriptを選択し、GPTという名前に変更する。

image.png

できたGPTファイルをダブルクリックして、編集ソフト(VisualStudioなど)を起動し、次の内容にする。
(try catchは省略)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

using OpenAI;
using OpenAI.Chat;
using System.ClientModel;

public class GPT : MonoBehaviour
{
    async void Start()
    {
        var apiKey = LoadApiKey();
        if (string.IsNullOrEmpty(apiKey)) return;

        OpenAIClient client = new OpenAIClient(new ApiKeyCredential(apiKey));

        var model = "gpt-4o-mini";
        // Chat用のClientを取得(機能ごとにClientが存在する)
        ChatClient chat = client.GetChatClient(model);
        List<ChatMessage> chatMessages = new List<ChatMessage>();

        // AIに送るメッセージ
        string message = "日本の著名人の名前を5人挙げて";
        chatMessages.Add(new UserChatMessage(message));

        // チャットの送信
        var response = await chat.CompleteChatAsync(chatMessages);

        // ChatGPTの返答
        var responseText = response.Value.Content[0].Text;
        Debug.Log($"ChatGPTの応答:{responseText}");
    }

    private string LoadApiKey(){
        // Assets直下の api_key.txt を参照
        var path = Path.Combine(Application.dataPath, "api_key.txt");

        if (!File.Exists(path)){
            Debug.LogError("api_key.txt が見つかりません: " + path);
            return null;
        }

        var key = File.ReadAllText(path).Trim();
        if (string.IsNullOrEmpty(key)){
            Debug.LogError("api_key.txt が空です");
            return null;
        }
        return key;
    }
}

サンプルコードの実行

プログラムを適当なオブジェクトに割り当てる。
ここでは、Cubeオブジェクトを用意する。

image.png

つくったcubeの一番下のadd componentからGPTプログラムを検索して、追加する。

image.png

実行

image.png

こんな感じで、Consoleタブに、返答が出力されればOK

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?