0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unityで発生した問題など

0
Posted at

Unityでゲームを作る上で発生した問題など

ほぼ自分用ですがUnityでゲームを作成する中で発生したエラー等を少しずつ書いていきます。(随時更新)

目次

  1. Resources.Loadで引っ掛かった所について

1.Resources.Loadで引っ掛かった所について

経緯

Resources.Loadを用いてAssets/Prefab/<Prefab Object>.prefabを読み込みましたが、hierarchyやGameなどのすべてのウィンドウで一切表示されませんでした。

以下、実際に実行したコードです。

Initialize.cs
    public void Awake()
    {

        for(int i = 0; i < (条件); i++)
        {
            var gameObject = Resources.Load<GameObject>("Prefab/<Prefab Object>");

            if (gameObject == null)
            {
                Debug.LogError("NULL");
                break;
            }
        }
        
        return;
    }

試した事

以下のコードを前項で記述したコードに追加し結果を得ました。

処理 結果
gameObject == null False
gameObject.scene.name ""
gameObject.scene.path NullPointerException

ゲームオブジェクト自体はNullになっていなかったため成功していると思われますが(実際には画面上に表示されていないので不明ですが)、ゲームオブジェクトがあるシーンを調べて見ると存在しない事がわかりました。

以上のことから、生成されたオブジェクトはAwake内の処理が終わると同時に消滅しているのではないかと考えられます。

解決策

Instantiateを用いてResources.Loadで生成したゲームオブジェクトを複製します。

以下、そのコードです。

Initialize.cs
    public void Awake()
    {
        var template = Resources.Load<GameObject>("Prefab/<Prefab Object>");
        
        for(int i = 0; i < (条件); i++)
        {
            var gameObject = Instantiate(template, new Vector3(0, 0, 0), new Quaternion());

            if (gameObject == null)
            {
                Debug.LogError("NULL");
                break;
            }
        }
        
        return;
    }

Instantiateを用いた所、オブジェクトは正常に生成されました。
Unityのドキュメントを閲覧してもResources.Loadのみで正常に動作するはずなのですが、結局原因はわかりませんでした。
どなたか知っているのであれば教えていただけたら幸いです。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?