[UNITY]2DRPG開発日誌 #17 配列の要素番号をアタッチ先からIndexOfで取得する方法

やりたいこと

やりたいことは、要は「配列から特定の要素番号を抽出する」というだけです。

しかし、いまやりたいのは「配列から直接抽出する」のではなく、「別の領域にアタッチされたオブジェクトが配列のどこに入っているのか」を探すこと。

つまり、上の画像でいうと「TestAttachに代入されているTestPrefabが、配列「TestPrefabs」のなかの、どのIndexに入っているのかを抽出したい」というものです。

上の画像でいうと「0」を抽出できればOKですね。

前提の説明

まず、「TestObject」にコンポーネント「Test.cs」を持たせています。「Test.cs」のコードは次のとおりです。

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

public class Test : MonoBehaviour
{
   public GameObject testAttach;
   public GameObject[] _TestPrefabs = new GameObject[1];
   private int testIndex;

   void Start()
   {
      testAttach = _TestPrefabs[0];
      testIndex = testAttach.IndexOf(_TestPrefabs); //←これが間違ってる
   }
}

public GameObject[] _TestPrefabs = new GameObject[1];」によりInspectorに生成された配列に「TestPrefub」をアタッチしています。

さらに、「testAttach = _TestPrefabs[0];」によって、その配列にアタッチしたTestPrefubをTestAttachに代入しています(赤い矢印)。

※TestPrefabはScene内にはなく、Projectウインドウから直接アタッチしています。
※「TestPrefab」はカラッポのオブジェクトです。

エラーの内容

まず、先に記載したコードでは次のようなエラーとなります。

Assets\Scripts\Test\Test.cs(16,32): error CS1061: 'GameObject' does not contain a definition for 'IndexOf' and no accessible extension method 'IndexOf' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

これは「お前 IndexOf の使い方が間違ってるぞ!」という意味です。

解決方法

正しいコードは次のとおりです。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;   //←正解

public class Test : MonoBehaviour
{
   public GameObject testAttach;
   public GameObject[] _TestPrefabs = new GameObject[1];
   private int testIndex;

   void Start()
   {
      testAttach = _TestPrefabs[0];
      testIndex = Array.IndexOf(_TestPrefabs,testAttach);   //←正解
   }
}

まず、IndexOfの使い方は「testIndex = Array.IndexOf(_TestPrefabs,testAttach);」が正しい記述法です

次に、この記法を使うためには冒頭に「using System;」と書く必要があります。

これにより、testIndexに「0」が代入されます。

基本的なことですが、調べ方がわからず苦労しました…。

UNITY
スポンサーリンク
Share
Follow Us
KITTYPOOL