Unity:Singleton DontDestroyOnLoad构建错误

时间:2016-12-27 18:17:27

标签: c# android unity3d singleton unity5

我正在使用XMGUnityLib插件。该程序在编辑器中运行良好,没有任何错误但是当我尝试构建它(Android)然后在推送apk步骤时它给出了这个错误:

this.akeInputReverse

XMGSingleton.cs:

InvalidOperationException: The following game object is invoking the DontDestroyOnLoad method: AnalyticsManager. Notice that DontDestroyOnLoad can only be used in play mode and, as such, cannot be part of an editor script.
XMGSingleton`1[XMGAnalyticsManager].get_Instance () (at Assets/XMG/UnityLib/Util/XMGSingleton.cs:28)
AndroidStorePostProcess.OnPostprocessScene () (at Assets/Editor/AndroidStorePostProcess.cs:32)
UnityEditor.HostView:OnGUI()

XMGAnalyticsManager.cs:

using UnityEngine;
using System.Collections;
using System;

/// <summary>
/// XMG singleton base Class.
/// Inherit your Manager Monobehavior classes that you want to be Singletons
/// </summary>
public abstract class XMGSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T instance;
    /// <summary>
    /// Returns the instance of this singleton
    /// Make sure we don't get destroyed on Scene Load
    /// </summary>
    public static T Instance {
        get {

            if(instance == null) {
                instance = (T) FindObjectOfType(typeof(T));

                if (instance == null) {
                   Debug.LogError("An instance of " + typeof(T) + 
                      " is needed in the scene, but there is none.");
                    return null;
                }

                DontDestroyOnLoad(instance.gameObject);
            }
            return instance;
        }
    }

    #region Public Methods

    public static bool HasInstance {
        get {
            if( (T) FindObjectOfType(typeof(T)) != null ) {
                return true;
            } else {
                return false;
            }
        }
    }

    /// <summary>
    /// Helper to cast the Instance to the Type provided
    /// </summary>
    public static Type MyInstance<Type> () {
        return (Type)(object)Instance;
    }

    #endregion
}

这个单例类是否正确编码?如果是的话,可能是什么问题? 任何帮助将不胜感激。 谢谢:))

1 个答案:

答案 0 :(得分:0)

你有一个继承自这个类的“编辑器脚本”吗?如果是这样,那么很可能这就是造成错误的原因。如果您不确定这意味着什么,请尝试在项目中查找名为Editor的文件夹并查看其脚本。或者尝试搜索using UnityEditor;并且继承自Editor的任何脚本,如下所示:public class Name : Editor并使其不从此类继承。

另一个解决方案是尝试评论DontDestroyOnLoad行(XMGSingleton.cs中的第26行)并将其放在您需要的位置。

转到您正在使用此脚本的对象,并执行以下操作:

void Awake()
{
    if (instance == null)
    {
        DontDestroyOnLoad(gameObject);
        instance = this;
    }
    else
        if (instance != this)
            Destroy(gameObject);
}