How can I check if a object in the hierarchy have been destroyed using EditorWindow type script ?
Near the bottom of the script I'm checking if the file is exist on the hard disk and if the file length is large then 0. But now I also want to check if a GameObject from the selection List have been destroyed as also a condition to turn on enable true the button.
To test it I'm going to the unity editor and just delete one of the objects in the Hierarchy. But then I'm getting exception on the line:
GameObject.Find(tempTransformSelection[i].name) == null
Since the I deleted the object and it's destroyed there is no logic to check if it's null so in the editor I'm getting this exception:
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
So my question is how to check if object is exist or not in the hierarchy without getting this exception ? I want to enable true the button if one or more gameobjects in the selections List is not exist in the hierarchy.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Prefab : EditorWindow
{
[SerializeField] private GameObject prefab;
List<Transform> transformSelection = new List<Transform>();
List<Transform> tempTransformSelection = new List<Transform>();
[MenuItem("Tools/Prefab")]
static void CreatePrefab()
{
int width = 340;
int height = 150;
int x = (Screen.currentResolution.width - width) / 2;
int y = (Screen.currentResolution.height - height) / 2;
GetWindow<Prefab>().position = new Rect(x, y, width, height);
}
private void OnGUI()
{
var selections = Selection.objects.OfType<GameObject>().ToList();
if (selections.Count > 0)
{
for (var i = selections.Count - 1; i >= 0; --i)
{
var selected = selections[i];
transformSelection.Add(selected.transform);
}
TransformSaver.SaveTransform(transformSelection.ToArray());
tempTransformSelection = transformSelection;
transformSelection = new List<Transform>();
}
var file = @"d:\json\json.txt";
FileInfo fi = new FileInfo(file);
for (int i = 0; i < tempTransformSelection.Count(); i++)
{
if (File.Exists(@"d:\json\json.txt") && fi.Length > 0 &&
GameObject.Find(tempTransformSelection[i].name) == null)
{
GUI.enabled = true;
break;
}
else
{
GUI.enabled = false;
}
}
if (GUILayout.Button("Test Loading"))
{
TransformSaver.LoadTransform();
}
}
}
Answer by Ermiq · Aug 28, 2018 at 02:13 AM
Just don't use GameObject.Find. Use only tempTransformSelection[i] == null.