Referrence to prefab as GameObject type

Hello, out there.

Help needed.

I have a variable in some script:

    public GameObject firstKeyPrefab = null;

I would like to add reference to prefab to this variable.

If I do it thru inspector by grag-and-drop prefab from Asset folder evrething are correct.

But if I do it thru:

Object obj = Resources.Load("Key3");
    firstKeyPrefab = obj;

I have an error.

Assets\Scripts\SceneInitials.cs(50,22): error CS0266: Cannot implicitly convert type ‘UnityEngine.Object’ to ‘UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)

Can you advise me how to convert refference to prefab from “Object” type to “GameObject” one or directly get refference to prefab as GameObject type, please?

  • GameObject obj = Resources.Load(“Key3”);

try that implementation.

Hello, Homicide.
It works, thank you!
I have some other question.
If I can understand, “Resources.Load” works just with object placed in Resources folder.
Is there any way to load prefabs from folder other than “Resources”?

Sure, but none are as straight forward and easy as using the resources folder as you are. You can also skip right past loading them like that, and simply feed references to your scripts through serialized fields that will allow you to instantiate and such as you require.

But, in short, the simplest method, other than direct serialized references, is to do just what you are doing.

Homicide,
Thank you again!