Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Referrence to prefab as GameObject type

Discussion in 'Scripting' started by AlexeyFatnev, Mar 5, 2023.

  1. AlexeyFatnev

    AlexeyFatnev

    Joined:
    Sep 9, 2022
    Posts:
    3
    Hello, out there.

    Help needed.

    I have a variable in some script:

    Code (CSharp):
    1.     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:

    Code (CSharp):
    1. Object obj = Resources.Load("Key3");
    2.     firstKeyPrefab = obj;
    3.  
    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?
     
  2. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    664
    1. GameObject obj = Resources.Load<GameObject>("Key3");
    try that implementation.
     
  3. AlexeyFatnev

    AlexeyFatnev

    Joined:
    Sep 9, 2022
    Posts:
    3
    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"?
     
  4. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    664
    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.
     
  5. AlexeyFatnev

    AlexeyFatnev

    Joined:
    Sep 9, 2022
    Posts:
    3
    Homicide,
    Thank you again!