What is the correct way to check that a resource exists before instantiating it? Sometime I delete resources and forget to remove the instantiation from all my scripts
From the docs on Resources.Load: This method returns the asset at path if it can be found, otherwise it returns null.
However using such a check for your usecase has a lot in common with covering a large gap in a wall with newspaper.
Not really, let’s say I’m instantiating some cosmetic stuff that is isn’t important, then delete the prefab for what ever reason but forget to find the code that instantiated it. I have thousands of prefabs, lots not instantiated. It’s just a check like any other check we do a thousand times, if (something != null) then do whatever…
Which is precisely why you should avoid writing code that depends on “magic strings”. Instead you should write code that moves the responsibility from you to the compiler and/or the game engine.
If that’s not possible you should minimize the number of locations that it can be in. One way to do this is a static class with methods like the following:
public static GameObject Arrow()
{
var resource = (GameObject)Resources.Load("Props/Arrow");
if (resource == null)
Debug.LogError("Arrow prefab not found.");
return resource;
}