Reputation: 71
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];
}
}
Upvotes: 1
Views: 817
Reputation: 1435
You have to set the gameLoader
variable before trying to access it. Otherwise its value will always be null
by default. There are lots of ways to do this. The simpler one is to just search for it in the scene using FindObjectOfType
. Just add this to your SceneController's Awake
:
void Awake ()
{
gameLoader = FindObjectOfType<GameLoader>();
}
Remember that FindObjectOfType
should be used only in one-time operations:
Please note that this function is very slow. It is not recommended to use this function every frame. In most cases you can use the singleton pattern instead.
Upvotes: 6