I want to create a GameLoader to load my sprites and then a SceneController to create the game objects. I store the sprite in a dictionary in GameLoader, to get the sprite I want to make a function to receive a specific sprite from the GameLoader. It was working when it was in one Class but now it are two classes I have problems getting the Sprite. I get this error
NullReferenceException: Object reference not set to an instance of an object
SceneController.createGeometry () (at Assets/Controllers/SceneController.cs:18)
SceneController.Start () (at Assets/Controllers/SceneController.cs:13)
SceneController.cs
using System;
using System.Linq;
using UnityEngine;
using System.Collections.Generic;
public class SceneController : MonoBehaviour {
string[] geometryObjects = { "cube", "cube", "circle", "circle", "cube_small" };
int objectCount = 5;
GameLoader gameLoader;
void Start () {
createGeometry();
}
void createGeometry() {
foreach (string geometryObject in geometryObjects) {
Debug.Log(gameLoader.getGeometrySprite(geometryObject));
GameObject geometryGameObject = new GameObject();
geometryGameObject.name = geometryObject;
geometryGameObject.tag = "Geometry";
geometryGameObject.transform.position = new Vector3(0,0,0);
geometryGameObject.AddComponent<SpriteRenderer>().sprite = gameLoader.getGeometrySprite(geometryObject);
geometryGameObject.AddComponent<Rigidbody2D>();
geometryGameObject.AddComponent<BoxCollider2D>();
}
}
}
GameLoader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameLoader : MonoBehaviour {
Dictionary<string, Sprite> geometrySprites;
void Awake () {
LoadSprites();
}
void LoadSprites() {
geometrySprites = new Dictionary<string, Sprite>();
Sprite[] geometrySpritesResources = Resources.LoadAll<Sprite>("Images/Geometry");
foreach(Sprite geometrySpritesResource in geometrySpritesResources) {
geometrySprites[geometrySpritesResource.name] = geometrySpritesResource;
}
}
public Sprite getGeometrySprite(string spriteName) {
return geometrySprites[spriteName];
}
}