How check if a resource exists before instantiating

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

I’m using something like this,

Arrow = (GameObject)Instantiate(Resources.Load("Props/Arrow"),transform.position, Quaternion.Euler(new Vector3(0, 90, 0)));

Want to make sure that the Arrow resource is there before I try to Instantiate it.

Thanks,

V

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.

I wouldn’t check for this at runtime. You should search your codebase and remove the code that references these resources.

1 Like

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…

hmm, so the answer is no? I would, and could and should… but I forget as I am lowly human…

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.

https://en.wikipedia.org/wiki/Magic_string

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;
}

Then you can just instantiate it like this:

arrow = Instantiate(MyStaticClass.Arrow(), transform.position, Quaternion.Euler(new Vector3(0, 90, 0)));

Thanks Ryiah