在Unity的另一个类中从Dictionary接收值

时间:2018-07-20 05:01:19

标签: c# unity3d

我想创建一个GameLoader来加载我的精灵,然后创建一个SceneController来创建游戏对象。我将子画面存储在GameLoader中的词典中,以获取我想使函数从GameLoader接收特定子画面的子画面。在一堂课的时候,它一直在工作,但是现在到了两堂课,我在获取Sprite时遇到了问题。我收到此错误

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];
    }
}

1 个答案:

答案 0 :(得分:5)

您必须先设置gameLoader变量,然后才能访问它。否则,默认情况下其值将始终为null。有很多方法可以做到这一点。比较简单的一种就是使用FindObjectOfType在场景中进行搜索。只需将其添加到SceneController的Awake

void Awake () 
{
    gameLoader = FindObjectOfType<GameLoader>();
}

请记住,FindObjectOfType仅应用于一次操作:

  

请注意,此功能非常慢。不建议   每帧使用此功能。在大多数情况下,您可以使用单例   模式。