Beispiel #1
0
    public static T Load(string filename, string directory)
    {
#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
        string path = GetPath(directory, filename);
        if (File.Exists(path))
        {
            string dataAsJson = File.ReadAllText(path);
#if UNITY_EDITOR
            T      data  = new T();
            object boxed = data;
            EditorJsonUtility.FromJsonOverwrite(dataAsJson, boxed);
            data = (T)boxed;
#else
            T data = JsonUtility.FromJson <T>(dataAsJson);
#endif
            return(data);
        }
        else
        {
            Debug.LogWarning("Failed to deserialize save file: file not found.");
        }
        return(default(T));
    }
Beispiel #2
0
 protected EditorJsonAsset(string json)
 {
     if (!string.IsNullOrEmpty(json))
     {
         EditorJsonUtility.FromJsonOverwrite(json, this);
     }
 }
Beispiel #3
0
        protected override void OnEnable()
        {
            base.OnEnable();

            if (settings == null)
            {
                settings = new SettingsData();
            }

            EditorJsonUtility.FromJsonOverwrite(EditorPrefs.GetString("P3dPainter.Settings"), settings);

            autoRepaintOnSceneChange = true;

            previewUtil = new PreviewRenderUtility(true);

            previewUtil.camera.clearFlags    = CameraClearFlags.Skybox;
            previewUtil.camera.nearClipPlane = 0.01f;
            previewUtil.camera.farClipPlane  = 10000.0f;
            previewUtil.camera.fieldOfView   = 60.0f;

            thumbnailUtil = new PreviewRenderUtility(false);

            thumbnailUtil.camera.clearFlags      = CameraClearFlags.Color;
            thumbnailUtil.camera.backgroundColor = Color.clear;
            thumbnailUtil.camera.nearClipPlane   = 0.01f;
            thumbnailUtil.camera.farClipPlane    = 1000.0f;
            thumbnailUtil.camera.fieldOfView     = 15.0f;

            thumbnailUtil.camera.transform.position = Vector3.back * 4.0f;
            thumbnailUtil.camera.transform.rotation = Quaternion.identity;

            thumbnailUtil.lights[0].transform.rotation = Quaternion.Euler(30.0f, 320.0f, 0.0f);
            thumbnailUtil.lights[1].transform.rotation = Quaternion.Euler(330.0f, 85.0f, 0.0f);
        }
Beispiel #4
0
    private static void CreateScriptableObject(string path)
    {
        EnsureDirectoryExists(SCRIPTABLE_OBJECT_DESTIONATION_PATH);

        string jsonFileName = Path.GetFileNameWithoutExtension(path);

        string destinationPath = SCRIPTABLE_OBJECT_DESTIONATION_PATH + jsonFileName + ".asset";

        var gm = AssetDatabase.LoadAssetAtPath <TransformData>(destinationPath);

        if (gm == null)
        {
            gm = ScriptableObject.CreateInstance <TransformData>();
            AssetDatabase.CreateAsset(gm, destinationPath);
        }

        string dataAsJson = File.ReadAllText(path, System.Text.Encoding.UTF8);

        EditorJsonUtility.FromJsonOverwrite(dataAsJson, gm.item);

        EditorUtility.SetDirty(gm);

        AssetDatabase.Refresh();

        AssetDatabase.SaveAssets();
    }
        private void Deserialize()
        {
            m_gameObject           = new GameObject();
            m_gameObject.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
            m_gameObject.name      = (string.IsNullOrEmpty(m_newGameObjectName)) ? "New GameObject" : m_newGameObjectName;

            if (!string.IsNullOrEmpty(m_instanceData))
            {
                var decoded = CustomScriptUtility.DecodeString(m_instanceData);
                EditorJsonUtility.FromJsonOverwrite(decoded, m_gameObject);
            }

            if (m_attachedComponents == null)
            {
                m_attachedComponents = new List <ComponentInfo> ();
            }
            SortComponents();

            foreach (var info in m_attachedComponents)
            {
                info.Restore(m_gameObject);
            }

            if (m_gameObjectEditor == null)
            {
                m_gameObjectEditor = Editor.CreateEditor(m_gameObjectEditor);
            }
        }
Beispiel #6
0
        private static IEnumerator Execute()
        {
            string rawText = localTestData;

            if (string.IsNullOrWhiteSpace(rawText))
            {
                using (UnityWebRequest req = UnityWebRequest.Get(URI_VERSION_JSON))
                {
                    yield return(req.SendWebRequest());

                    if (req.isHttpError || req.isNetworkError)
                    {
                        Debug.LogWarningFormat("[WF][Version] An NetworkError was occured in version checking: {0}", req.error);
                        yield break;
                    }
                    rawText = req.downloadHandler.text;
                }
            }
            if (string.IsNullOrWhiteSpace(rawText))
            {
                yield break;
            }

            var version = new WFVersionInfo();

            EditorJsonUtility.FromJsonOverwrite(rawText, version);

            if (version.HasValue())
            {
                version.downloadPage = URI_HEAD + version.downloadPage;
                WFCommonUtility.SetLatestVersion(version);
                Debug.LogFormat("[WF][Version] VersionCheck Succeed, LatestVersion is {0}", version.latestVersion);
            }
        }
    public static void InstanceActor(Actor current, Transform parent)
    {
        Scene scene = SceneManager.GetActiveScene();

        GameObject currentGO = new GameObject(current.Name);

        currentGO.transform.parent = parent;
        currentGO.tag   = current.Tag;
        currentGO.layer = current.Layer;
        currentGO.transform.localPosition    = new Vector3(current.Transform.Position.x, current.Transform.Position.y, current.Transform.Position.z);
        currentGO.transform.localScale       = new Vector3(current.Transform.Scale.x, current.Transform.Scale.y, current.Transform.Scale.z);
        currentGO.transform.localEulerAngles = new Vector3(current.Transform.Rotation.x, current.Transform.Rotation.y, current.Transform.Rotation.z);
        foreach (ActorComponent comp in current.Components)
        {
            Component added = currentGO.AddComponentExt(comp.Type, comp.Asm);
            if (added != null)
            {
                EditorJsonUtility.FromJsonOverwrite(comp.SerializedValues, added);
            }
        }
        foreach (Actor act in current.Children)
        {
            InstanceActor(act, currentGO.transform);
        }
    }
            public void Restore(GameObject o)
            {
                UnityEngine.Assertions.Assert.IsNotNull(m_typeInfo);

                if (m_componentType == null)
                {
                    m_componentType = Type.GetType(m_typeInfo);
                }
                UnityEngine.Assertions.Assert.IsNotNull(m_componentType);

                m_component = o.GetComponent(m_componentType);
                if (m_component == null)
                {
                    m_component = o.AddComponent(m_componentType);
                    if (m_componentData != null)
                    {
                        EditorJsonUtility.FromJsonOverwrite(CustomScriptUtility.DecodeString(m_componentData), m_component);
                    }
                }

                if (m_componentEditor == null)
                {
                    m_componentEditor = Editor.CreateEditor(m_component);
                }
            }
        public static void Patch(string platform)
        {
            var p        = Application.dataPath + DevCacheDirectory + platform + AssetBundlePath.kSlash + AssetBundlePath.kPackCfg;
            var jsonData = File.ReadAllText(p);
            var cfg      = new PackageCfg();

            EditorJsonUtility.FromJsonOverwrite(jsonData, cfg);

            var tmpDir = Application.dataPath + "/tempDir";

            if (Directory.Exists(tmpDir))
            {
                Directory.Delete(tmpDir, true);
            }
            var patchCfg = new PackageCfg();

            patchCfg.PatchVersion = PackEditorWin.GetCfg().PatchVersion;
            var parentPath = Application.dataPath + DevCacheDirectory + platform;

            var codePatchFile = parentPath + AssetBundlePath.kSlash + AssetBundlePath.kCodePatchFile;

            if (File.Exists(codePatchFile))
            {
                cfg.Files.Add(new FileCfg(CommonTool.CalFileMD5(codePatchFile), AssetBundlePath.kCodePatchFile));
            }
            for (int i = 0; i < cfg.Files.Count; ++i)
            {
                var f   = cfg.Files[i];
                var md5 = CommonTool.CalFileMD5(parentPath + AssetBundlePath.kSlash + f.Path);
                if (Path.GetExtension(f.Path) == AssetBundleMgr.instance.kPatchFileExt || md5 != f.MD5 && Path.GetExtension(f.Path) != AssetBundlePath.kPackCfgSuffix)
                {
                    patchCfg.Files.Add(new FileCfg(md5, f.Path));

                    var t = tmpDir + AssetBundlePath.kSlash + f.Path;
                    if (!Directory.Exists(Path.GetDirectoryName(t)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(t));
                    }
                    File.Copy(parentPath + AssetBundlePath.kSlash + f.Path, t);
                }
            }
            if (patchCfg.Files.Count != 0)
            {
                using (var sw = File.CreateText(tmpDir + AssetBundlePath.kSlash + AssetBundlePath.kPatchCfg))
                {
                    sw.Write(EditorJsonUtility.ToJson(patchCfg));
                }
                ZipHelper.ZipDirectoryDirect(tmpDir, Application.dataPath + DiffPatchDirectory + platform + AssetBundlePath.kPatchZipRes);
                TimeLogger.LogYellow(platform + "差异包生成成功");

                if (Directory.Exists(tmpDir))
                {
                    Directory.Delete(tmpDir, true);
                }
            }
            else
            {
                Debug.LogError("no different patch");
            }
        }
        private static void LoadFromJson()
        {
            preferences = ScriptableObject.CreateInstance <HierarchyPreferences>();
            var json = EditorPrefs.GetString(PreferencePath);

            EditorJsonUtility.FromJsonOverwrite(json, preferences);
        }
Beispiel #11
0
        public static void ImportAllJSONInDirectoryToGraphFromDialog()
        {
            var folderSelected =
                EditorUtility.OpenFolderPanel("Select folder contains JSON files to import", Application.dataPath + "..", "");

            if (string.IsNullOrEmpty(folderSelected))
            {
                return;
            }

            var newAssetFolder = CreateFolderForImportedAssets();

            var filePaths = FileUtility.GetAllFilePathsInFolder(folderSelected);

            foreach (var path in filePaths)
            {
                var ext = Path.GetExtension(path).ToLower();
                if (ext != ".json")
                {
                    continue;
                }
                var jsonContent = File.ReadAllText(path, System.Text.Encoding.UTF8);
                var name        = Path.GetFileNameWithoutExtension(path);

                var graph = ScriptableObject.CreateInstance <Model.ConfigGraph>();
                EditorJsonUtility.FromJsonOverwrite(jsonContent, graph);
                var graphPath = FileUtility.PathCombine(newAssetFolder, string.Format("{0}.asset", name));
                AssetDatabase.CreateAsset(graph, graphPath);
            }
        }
Beispiel #12
0
        public static Model.ConfigGraph ImportJSONToGraphFromDialog(Model.ConfigGraph graph)
        {
            string fileSelected = EditorUtility.OpenFilePanelWithFilters("Select JSON files to import", Application.dataPath, new string[] { "JSON files", "json", "All files", "*" });

            if (string.IsNullOrEmpty(fileSelected))
            {
                return(null);
            }

            string name = Path.GetFileNameWithoutExtension(fileSelected);

            var jsonContent = File.ReadAllText(fileSelected, System.Text.Encoding.UTF8);

            if (graph != null)
            {
                Undo.RecordObject(graph, "Import");
                EditorJsonUtility.FromJsonOverwrite(jsonContent, graph);
            }
            else
            {
                graph = ScriptableObject.CreateInstance <Model.ConfigGraph>();
                EditorJsonUtility.FromJsonOverwrite(jsonContent, graph);
                var newAssetFolder = CreateFolderForImportedAssets();
                var graphPath      = FileUtility.PathCombine(newAssetFolder, string.Format("{0}.asset", name));
                AssetDatabase.CreateAsset(graph, graphPath);
            }
            return(graph);
        }
Beispiel #13
0
            public Material To()
            {
                if (string.IsNullOrEmpty(m_assetGuid))
                {
                    Material mat = new Material(Shader.Find("Standard"));
                    EditorJsonUtility.FromJsonOverwrite(m_jsonData, mat);
                    mat.name = m_name;
                    return(mat);
                }
                else
                {
                    string path    = AssetDatabase.GUIDToAssetPath(m_assetGuid);
                    var    objects = AssetDatabase.LoadAllAssetsAtPath(path);
                    for (int i = 0; i < objects.Length; ++i)
                    {
                        Material mat = objects[i] as Material;

                        if (mat == null)
                        {
                            continue;
                        }

                        if (mat.name == m_name)
                        {
                            return(mat);
                        }
                    }

                    return(AssetDatabase.LoadAssetAtPath <Material>(path));
                }
            }
Beispiel #14
0
        [DidReloadScripts] private static void Phase2()
        {
            var guids = PlayerPrefs.GetString("Askowl.OnScriptReload").Split(';').Reverse();

            PlayerPrefs.DeleteKey("Askowl.OnScriptReload");
            foreach (var guid in guids)
            {
                if (!string.IsNullOrEmpty(guid))
                {
                    var typeName = PlayerPrefs.GetString(guid);
                    var json     = PlayerPrefs.GetString($"{guid}-Content");
                    PlayerPrefs.DeleteKey(guid);
                    var type = Type.GetType(typeName);
                    if (type == null)
                    {
                        throw new Exception($"Unknown type {typeName}'");
                    }
                    var target = (type.IsAssignableFrom(typeof(ScriptableObject)))
                         ? ScriptableObject.CreateInstance(type)
                         : ObjectFactory.CreateInstance(type);
                    if (target == null)
                    {
                        throw new Exception($"Can't instantiate '{typeName}'");
                    }
                    EditorJsonUtility.FromJsonOverwrite(json, target);
                    (target as IOnScriptReload)?.OnScriptReload();
                }
            }
        }
Beispiel #15
0
    static void DoIt()
    {
        var txt     = AssetDatabase.LoadAssetAtPath <TextAsset>("Assets/UAds/VERSION.txt");
        var setting = AssetDatabase.LoadAssetAtPath <UAds.UAdsSetting>("Assets/UAds/UAdsSettings.asset");
        // データ初期化前に設定保持しておき、終了したら復元する
        var original = EditorJsonUtility.ToJson(setting);

        //  export前に初期設定にする
#if UNITY_ADS || UNITY_MONETIZATION
        setting.unityAds.androidGameId = "";
        setting.unityAds.iOSGameId     = "";
#endif

#if ENABLE_ADCOLONY
        setting.adColony.androidSetting = new UAds.UAdsSetting.AdColoySetting.Setting();
        setting.adColony.iOSSetting     = new UAds.UAdsSetting.AdColoySetting.Setting();
#endif

        UAds.Editor.UAdsSettingHelper.SaveUAdsSettings(setting);

        EditorUtility.DisplayProgressBar("Export Package", "Processing...", 0.1f);
        var packageName = "uads.unitypackage";
        try {
            AssetDatabase.ExportPackage("Assets/UAds", packageName, ExportPackageOptions.Recurse);
            EditorUtility.DisplayProgressBar("Export Package", "", 1f);
            Debug.Log("create " + packageName);
        }
        finally {
            // 復元処理
            EditorUtility.ClearProgressBar();
            EditorJsonUtility.FromJsonOverwrite(original, setting);
            UAds.Editor.UAdsSettingHelper.SaveUAdsSettings(setting);
        }
    }
            void RestoreComponent(GameObject go, SerializedComponent serializedComponent)
            {
                Component component = null;

                if (!loadedAssemblies.ContainsKey(serializedComponent.assemblyName))
                {
                    loadedAssemblies.Add(serializedComponent.assemblyName, Assembly.Load(serializedComponent.assemblyName));
                }
                Type type = loadedAssemblies[serializedComponent.assemblyName].GetType(serializedComponent.typeName);

                Debug.Assert(type != null, "Type '" + serializedComponent.typeName + "' not found in assembly '" + serializedComponent.assemblyName + "'");

                if (type == typeof(Transform))
                {
                    component = go.transform;
                }
                else
                {
                    component = Undo.AddComponent(go, type);
                }

//				bool restore = true;
//				if(restore) {
                EditorJsonUtility.FromJsonOverwrite(serializedComponent.serializedData, component);
                RestoreObjectReference(serializedComponent.savedInstanceIDs, component);
//				}
                deserializedObjects.Add(component);
                deserializedComponents.Add(new DeserializedComponent(serializedComponent, component));
            }
Beispiel #17
0
    public static GameObject CreateClone(GameObject source)
    {
        var jsonComponents = new List <string>();
        var comps          = source.GetComponents <Component>();
        var types          = new List <Type>();

        foreach (var comp in comps)
        {
            Debug.Log(comp.name);
            string json = EditorJsonUtility.ToJson(comp);
            types.Add(comp.GetType());
            Debug.Log(json);
            jsonComponents.Add(json);
        }

        var clone = new GameObject {
            name = source.name, tag = source.tag, layer = source.layer
        };

        for (var i = 0; i < jsonComponents.Count; i++)
        {
            var comp = types[i] == typeof(Transform) ? clone.transform : clone.AddComponent(types[i]);
            EditorJsonUtility.FromJsonOverwrite(jsonComponents[i], comp);
        }

        foreach (Transform child in source.transform)
        {
            CreateClone(child.gameObject).transform.parent = clone.transform;
        }

        return(clone);
    }
Beispiel #18
0
 private void OnEnable()
 {
     // get data
     JsonUtility.FromJsonOverwrite(PlayerPrefs.GetString(saveKey), this);
     EditorJsonUtility.FromJsonOverwrite(PlayerPrefs.GetString(saveKey), this);
     Debug.Log("overwrite data");
 }
        public static T Deserialize(string json)
        {
            var value = (object)Activator.CreateInstance <ValueWrapper <T> >();

            EditorJsonUtility.FromJsonOverwrite(json, value);
            return(((ValueWrapper <T>)value).m_Value);
        }
    /// <summary>
    /// Load favorites and window preferences
    /// </summary>
    private void LoadPrefs()
    {
        if (EditorPrefs.HasKey(showBuildScenesPrefKey))
        {
            showBuildScenes = EditorPrefs.GetBool(showBuildScenesPrefKey);
        }

        if (EditorPrefs.HasKey(showAllScenesPrefKey))
        {
            showAllScenes = EditorPrefs.GetBool(showAllScenesPrefKey);
        }

        if (EditorPrefs.HasKey(showFavoriteScenesPrefKey))
        {
            showFavorites = EditorPrefs.GetBool(showFavoriteScenesPrefKey);
        }

        if (PlayerPrefs.HasKey(favoriteScenesPrefKey))
        {
            string favoritesAsJson = PlayerPrefs.GetString(favoriteScenesPrefKey);

            if (favoritesAsJson != "")
            {
                try {
                    EditorJsonUtility.FromJsonOverwrite(favoritesAsJson, favorites);
                } catch (Exception e) {
                }
            }
        }
    }
Beispiel #21
0
        // override InitializeExtraDataInstance to set up the data.
        protected override void InitializeExtraDataInstance(Object extraTarget, int targetIndex)
        {
            var stack = (ShaderPackage)extraTarget;

            string fileContent = File.ReadAllText(((AssetImporter)targets[targetIndex]).assetPath);

            EditorJsonUtility.FromJsonOverwrite(fileContent, stack);
        }
Beispiel #22
0
        private ScriptIconsDatabase ReadDatabase()
        {
            var database = new ScriptIconsDatabase();

            EditorJsonUtility.FromJsonOverwrite(File.ReadAllText(m_databaseFilePath), database);

            return(database);
        }
 public void Load()
 {
     if (EditorPrefs.HasKey(DependencyViewerSettingsSaveName))
     {
         var data = EditorPrefs.GetString(DependencyViewerSettingsSaveName);
         EditorJsonUtility.FromJsonOverwrite(data, this);
     }
 }
Beispiel #24
0
        static void SetupStore()
        {
            var shareState = new ShareState();

            EditorJsonUtility.FromJsonOverwrite(SessionState.GetString(typeof(ConnectShareEditorWindow).Name, "{}"), shareState);

            _store = new Store <AppState>(ShareReducer.reducer, new AppState(shareState), ShareMiddleware.Create());
        }
Beispiel #25
0
 private void LoadStorage()
 {
     _storage = new Storage();
     if (EditorPrefs.HasKey(kPreferencesKey))
     {
         var preferencesJSON = EditorPrefs.GetString(kPreferencesKey);
         EditorJsonUtility.FromJsonOverwrite(preferencesJSON, _storage);
     }
 }
Beispiel #26
0
 public void Restore()
 {
     // Note: EditorJsonUtility.FromJsonOverwrite doesn't dirty settings
     EditorJsonUtility.FromJsonOverwrite(Contents, Target);
     if (IsDirty)
     {
         EditorUtility.SetDirty(Target);
     }
 }
Beispiel #27
0
        public static void Load(PaintParam param, string path)
        {
            string filePath = Path.Combine(path, SERIALIZED_NAME);

            if (File.Exists(filePath))
            {
                EditorJsonUtility.FromJsonOverwrite(File.ReadAllText(filePath), param);
            }
        }
Beispiel #28
0
        public static void OverwriteFromSerializedObject(Bootstrapper bootstrapper)
        {
            var jsonConfig = SessionState.GetString(SERIALIZED_BOOTSTRAPPER_JSON_KEY, null);

            if (!string.IsNullOrWhiteSpace(jsonConfig))
            {
                EditorJsonUtility.FromJsonOverwrite(jsonConfig, bootstrapper);
            }
        }
Beispiel #29
0
        static void TryLocalize()
        {
            var obj = (TextAsset)EditorGUIUtility.Load("HoshiyukiToonEditor/Localization/HoshiyukiToonEditor_" + Application.systemLanguage.ToString() + ".json");

            if (obj)
            {
                EditorJsonUtility.FromJsonOverwrite(obj.text, s_styles);
            }
        }
Beispiel #30
0
        protected override TData OnLoadSettings()
        {
            string text   = EditorPrefs.GetString(Key, "{}");
            var    target = ScriptableObject.CreateInstance <TData>();

            EditorJsonUtility.FromJsonOverwrite(text, target);

            return(target);
        }