How to load a prefab with Resources.Load() in unity?

38 views Asked by At

I've been trying to load pieces for a chess program which involves loading in a bunch of chess piece prefabs to load on the screen but for some reason it isn't working. Here's the code

white_pawn = (GameObject) Resources.Load("wP.prefab", typeof(GameObject));

But all it returns is

ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <fe7039efe678478d9c83e73bc6a6566d>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field,

I have tried putting it in a Resources folder : Assets/Resources/wP.prefab But it still won't work.

Any Ideas?

1

There are 1 answers

0
navarone On BEST ANSWER

Always look at the documentation when confused If see here how to properly use this function: https://docs.unity3d.com/ScriptReference/Resources.html

You will notice the file extension is omitted.

The proper line would for example be

 private GameObject whitePawn;
    private void Awake()
    {
         whitePawn = Resources.Load("wP") as GameObject;
    }

The other casts are also redundant.