- Home /
Why does FindObjectsOfType find objects earlier destroyed?
I have i loading script that first clears everything in the scene, instantiates a starting environment and finds an array of scripts.
public class LoaderScript : MonoBehaviour {
public UISliderScript[] sliders;
private string pathToInitObjects = "Prefabs/InitializationGenerated";
void Start() {
ClearScene ();
InitalizeStartingEnvironment ();
sliders = FindObjectsOfType(typeof(UISliderScript)) as UISliderScript[];
}
void ClearScene() {
foreach (GameObject obj in Object.FindObjectsOfType<GameObject>()) {
if (obj != this.gameObject) {
Destroy (obj);
}
}
}
void InitalizeStartingEnvironment() {
Object[] initObjects = Resources.LoadAll (pathToInitObjects, typeof(GameObject));
foreach (GameObject obj in initObjects) {
Instantiate (obj, obj.transform.position, transform.rotation);
}
}
}
The issue:
I first clear the scene where two scripts of the sought type are present and attached to individual gameobjects.
I then create a starting environment where two scripts of the sought type are present and attached to individual gameobjects.
I then want to find the two scripts in the starting environment (which i do) but i also find two more missing objects, which are a result of them being in the scene before i clear it. If i remove them from the scene before clearing, FindObjectsOfType will not find missing objects.
This tells my the the FindObjectsOfType finds objects that has been destroyed earlier.
Why is this happening to me? (I'd like to know why i am getting this wierd behaviour and not other alternative solutions)
EDIT: if i try to find the objects after all the start methods have been run i only find the two scripts and not the missing ones, which i want. But i really like to find everything at initialization.
Answer by Tasarran · Apr 26, 2017 at 04:37 PM
https://docs.unity3d.com/ScriptReference/Object.Destroy.html
The key phrase is the last sentence in the description: "Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering."
You might want to look into Object.DestroyImmediate or just delay your Initialize function until one frame later.
Yeah, it's counter-intuitive. The reason it works that way by default is that there may be scripts running on that object, or other scripts that may refer to that object. If you use DestroyImmediate, you have to be careful not to cause any script-crashing null reference errors in such cases.
Your answer
![](https://koobas.hobune.stream/wayback/20220612120716im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Flip over an object (smooth transition) 3 Answers