场景重新加载后不删除单例游戏对象引用的有效方法

Efficient way to not delete gameobject reference of singleton after scene reload

我有一个单例class,每次我重新加载场景时,我存储在变量中的对象引用都会被销毁

public class GameManager : MonoBehaviour
{
     private void Awake()
     {
         if (instance == null)
         {
             instance = this;
         }
         else
         {
             Destroy(this.gameObject);
         }
         DontDestroyOnLoad(this);

         Debug.Log("Scene reloaded");
    }


    void Start()
    {
        shapeSpawnerGO = GameObject.Find("SpawnShapesObj");
        scoreGO = GameObject.Find("ScoreText");
        lifeGo = GameObject.Find("LifeText");
    }

    public bool RedShapeStatus(int rcv_RedShapeIndex)
    {
        if (shapeSpawnerGO == null)
        {
            shapeSpawnerGO = GameObject.Find("SpawnShapesObj");
        }
        return shapeSpawnerGO.GetComponent<ShapeSpawnerChild>().listofRedShape[rcv_RedShapeIndex].activeSelf;     
    }
}

我所做的是检查 shapeSpawnerGO 是否为空,然后再次引用游戏对象。而且我认为这效率不高。还有其他方法可以解决这个问题吗?

当然还有其他方法可以做到这一点,但我的官方回答是"You're already doing it an acceptable way."你具体是这样说的:

"What I've done is check if shapeSpawnerGO is null then reference again the gameobject. And I think this is not efficient. Is there other way to solve this issue?"

你说你的代码唯一一次重新初始化变量是在场景 reloads.That 操作时间甚至无关紧要的时候。您实际上是在谈论优化完全不相关的东西。在重新加载期间重新初始化场景数据是正常场景加载的全部内容。

唯一的例外是,如果您的场景重新加载想法是您每隔几秒钟就会做的事情。如果您谈论的是场景重新加载的正常想法,即您加载游戏场景一次,然后在重新加载新场景之前继续 运行 游戏几分钟,那么没有理由担心此代码执行其正常的初始化行为。