由脚本创建的Unity新游戏对象不在相应的场景中

时间:2017-10-09 08:22:55

标签: c# unity3d singleton unity5

我修改单例以便它只适用于scene,我也删除了DontDestroyOnLoad()并将_instance重置为null。

但问题是,这个新的单身GameObject被放置在其他场景中。所以当场景卸载时,它不会破坏,因为它在其他场景上。

SingletonScene应位于Kanga1的相应场景中。

enter image description here

public class SingletonScene<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    private static object _lock = new object();

    public static T instance
    {
        get
        {
            lock (_lock)
            {
                if (_instance == null)
                {
                    _instance = (T)FindObjectOfType(typeof(T));

                    if (FindObjectsOfType(typeof(T)).Length > 1)
                    {
                        Debug.LogError("[Singleton] Something went really wrong " +
                            " - there should never be more than 1 singleton!" +
                            " Reopening the scene might fix it.");
                        return _instance;
                    }

                    if (_instance == null)
                    {
                        GameObject singleton = new GameObject();
                        _instance = singleton.AddComponent<T>();
                        singleton.name = "(SingletonScene) " + typeof(T).ToString();

                        Debug.Log("[SingletonScene] An instance of " + typeof(T) +
                            " is needed in the scene, so '" + singleton +
                            "' was created");
                    }
                    else
                    {
                        Debug.Log("[Error] this should not happen on SingletonScene " +
                            _instance.gameObject.name);
                    }
                }

                return _instance;
            }
        }
    }

    public void OnDestroy()
    {
        _instance = null;
    }
}

0 个答案:

没有答案