GameObject[] is not instantiated when using the C# hash table in Unity

Asked 1 years ago, Updated 1 years ago, 43 views

GameObject[]go1;
GameObject[]go2;
GameObject[]go3;
string [ ] tag = {"A", "B", "C" };

Dictionary <int, GameObject[]>Dict=new Dictionary<int, GameObject[]>();
Pict.Add(0,go1);
Pict.Add (1, go2);
Pict.Add(2,go3);

for (inti=0;i<tag.Length;i++)
{
    Pict[i] = GameObject.FindGameObjectsWithTag(tag[i]);
}

When I wrote the above code and tried to scan the batch of GameObjects acquired with tags using hash tables and iterations, I received an "uninstanced" error as follows:

NullReferenceException:Object reference not set to an instance of an object

How do I resolve the error that says it is not instantiated when retrieving the GameObject group in bulk?

unity3d c#

2022-09-30 11:50

3 Answers

It does not appear to be instantiated from go1 to go3, but

Dict.Add(0,go1);
Pict.Add (1, go2);
Pict.Add(2,go3);

If GameObject.FindGameObjectsWithTag() correctly returns an array of GameObject, I think it is not necessary.

string[]tag={"A", "B", "C"};
Dictionary <int, GameObject[]>dict=new Dictionary<int, GameObject[]>();
for (inti=0;i<tag.Length;i++)
{
    dict[i] = GameObject.FindGameObjectsWithTag(tag[i]);
}

Then, won't it work?


2022-09-30 11:50

It depends on how GameObject is configured in the array. If it is manually configured on the Inspector, etc. Before Awake for each GameObject added in Dictionary, If it is not instantiated, I think it is inevitable that an error will appear.

If the above processing appears to be performed by Awake in MonoBehavior, go to Start. I think it works fine.


2022-09-30 11:50

If you create several GameObjects such as Cube, set A, B, and C in the Tag, and add the script below to any GameObject in the Scene, it will work. What do you think?

using System.Collections.General;
using UnityEngine;
using System.Collections;

public class GameManager:MonoBehavior
{
    private static readonly string [] Tags = {"A", "B", "C"};

    private readonly Dictionary <int, GameObject[]>_dict=new Dictionary<int, GameObject[]>();
    private int_counter;

    void Start()
    {
        for (vari=0;i<Tags.Length;i++)
        {
            _dict[i] = GameObject.FindGameObjectsWithTags[i]);
        }
        StartCoroutine (SampleCoroutine());
    }

    IEnumerator SampleCoroutine()
    {
        while(true)
        {
            yield return new WaitForSeconds (2f);

            foreach(var targetObject in_dict [_counter%_dict.Count])
            {
                // Target GameObject extends vertically
                targetObject.transform.localScale+=newVector3(0,0.5f);
            }

            _counter++;
        }
    }
}


2022-09-30 11:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.