Search Unity

Resources.Load wont load prefabs into array

Discussion in 'Scripting' started by Dermakol, Nov 6, 2020.

  1. Dermakol

    Dermakol

    Joined:
    Nov 6, 2020
    Posts:
    2
    Got this code and for the love of god can not get the prefabs to load into the array and variable, feel like I am using the class wrong.

    Resources folder location is at Assets.
    Tried different syntax of casting, making the fields not static, instantiating the gameobjects on Load.
    Whatever I do, when debugging the Shapes array and EnemyBase var are always null.

    Code (CSharp):
    1.  
    2. using System;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6.  
    7. public class ResourceManager : MonoBehaviour
    8. {
    9.     private const string EnemyBasePATH = "EnemyBasePrefab/EnemyBase";
    10.     private const string ShapesPATH = "EnemyShapes";
    11.  
    12.     [SerializeField] public static GameObject[] Shapes;
    13.     [SerializeField] public static GameObject EnemyBase;
    14.  
    15.     void Awake() {
    16.         LoadShapes();
    17.         LoadEnemyBase();
    18.     }
    19.  
    20.     private void LoadEnemyBase() {
    21.         EnemyBase = Resources.Load(EnemyBasePATH, typeof(GameObject)) as GameObject;
    22.     }
    23.  
    24.     private void LoadShapes(){
    25.         Shapes = Resources.LoadAll(ShapesPATH, typeof(GameObject)) as GameObject[];
    26.     }
    27. }
    28.  
     
  2. Dermakol

    Dermakol

    Joined:
    Nov 6, 2020
    Posts:
    2
    Nevermind figured it out. The cast was bad, guess I need to pass it around as an Object instead of GameObject until I instantiate it.

    Code (CSharp):
    1. UnityEngine.Object[] shapesObjects = Resources.LoadAll(ShapesPATH, typeof(UnityEngine.Object));
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Just do it with the templated version:

    Code (csharp):
    1. GameObject[] enemies = Resources.LoadAll<GameObject>( enemyBasePath);