UnityでARアプリを作成してみる
以前ステップアップUnityを読んだ際に、書籍の手順に従ってAndroidのARアプリを作成しようとしたが、Gradle関連のエラーでビルド出来なかったため、今回は以下のリンク達を参考に、簡単なARアプリを作成してみたいと思う。
参考リンク
実行環境
Windows 11 Pro
Unity 2022.3.7f1
AR Foundation 5.0.7
手順
まずは新規の3Dプロジェクトを作成。次にBuild SettingsからPlatformをAndroidに変更。

そしてProject SettingsのPlayerから以下の設定を変更する。
・RederingのAutoGraphics APIのチェックを外す
・Graphics APIsからVulkanを削除
・IdetificationのMinimum API LevelをAndroid 7.1 ‘Nougat’ にする
Project SettingsのXR Plugin Managementからインストール。

インストールが完了したら、Google ARCoreにチェックを入れる。

次にPackage ManagerからAR Foundationがインストールされていることを確認。

Sample Sceneに含まれるMain Cameraを削除して、AR SessionとXR Origin (Mobile AR)を作成する。

HierarchyからCubeを追加し、Scaleを0.3に変更する。こちらも同様にPrefab化して、HierarchyのCubeは削除する。

画面のタップした位置にCubeを出現させるため、以下のC#Scriptを作成。
using System.Collections.Generic;
using UnityEngine.XR.ARFoundation;
using UnityEngine;
[RequireComponent(typeof(ARRaycastManager))]
public class PlaceOnPlane : MonoBehaviour
{
// タップ時に表示させるオブジェクト
[SerializeField]
private GameObject spawnObject;
private ARRaycastManager raycastManager;
private List<ARRaycastHit>hits = new List<ARRaycastHit>();
void Awake()
{
raycastManager = GetComponent<ARRaycastManager>();
}
void Update()
{
if (raycastManager.Raycast(Input.GetTouch(0).position, hits))
{
// タップされた場所にオブジェクトを生成
Instantiate(spawnObject, hits[0].pose.position, Quaternion.identity);
}
}
}
上のスクリプトはXR Originにアタッチして、Spawn Objectには先ほどCubeのPrefabを設定する。

実際にアプリをビルドして、実行した画像がこちら。ARアプリのテストに利用された飼い犬です。
