1
private List<GameObject> objectsToSave;

    private void Awake()
    {
        SaveSystem.Init();

        //objectsToSave = GameObject.FindGameObjectsWithTag("My Unique ID").ToList();
        var objectsWithGenerateGuid = GameObject.FindObjectsOfType<GenerateGuid>().ToList();
        if (objectsWithGenerateGuid.Count > 0)
        {
            for (int i = 0; i < objectsWithGenerateGuid.Count; i++)
            {
                objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);
            }
        }
    }

The first time I used FindGameObjectsWithTag but I had a problem for example with the MainCamera since I changed the objects I want to save tag to "My Unique ID" then the whole scene could not find the MainCamera. So instead find the objects to save by tag I thought to find them by components.

This is how I'm adding the Generate Guid component script to the objects I want to save :

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

public class GenerateAutomaticGuid : Editor
{
    [MenuItem("GameObject/Generate Guid", false, 11)]
    private static void GenerateGuid()
    {
        foreach (GameObject o in Selection.gameObjects)
        {
            var g = o.GetComponent<GenerateGuid>();
            if (!g) g = o.AddComponent<GenerateGuid>();
            g.GenerateGuidNum();
        }
    }
}

I can see that objectsWithGenerateGuid contains for example 5 items but when I'm trying to add them to the List objectsToSave I'm getting null exception on the line :

objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);

The main goal is to find all the objects that contains the script GenerateGuid and add them to the list objectsToSave.

Daniel Lip
  • 3,131
  • 5
  • 37
  • 84

1 Answers1

2

Try initializing the list first

private List<GameObject> objectsToSave = new List<GameObject>();

Since the count objectsWithGenerateGuid.Count is more than 0, then I presume that objectsToSave is null and that's why you are getting the null pointer exception.

Athanasios Kataras
  • 20,791
  • 3
  • 24
  • 45