Exemplo n.º 1
0
 public virtual bool Build(UnityEngine.Object obj)
 {
     Debug.LogError("can not build ab:" + AssetDatabase.GetAssetOrScenePath(obj));
     return(false);
 }
    private string convertScene()
    {
        string ret_str       = "";
        bool   isThereCamera = false;
        bool   isThereLight  = false;

        //sky
        if (enable_sky)
        {
            string add_str = "<a-sky ";

            Camera mainCamera = Camera.main;
            if (sky_color_from_MainCamera_Background && mainCamera)
            {
                add_str += "color=\"#" + ColorToHex(mainCamera.backgroundColor) + "\" ";
            }
            else
            {
                add_str += "color=\"#" + ColorToHex(sky_color) + "\" ";
            }

            if (sky_texture)
            {
                string texture_path = AssetDatabase.GetAssetPath(sky_texture);
                string new_path     = export_path + "/images/" + Path.GetFileName(texture_path);
                //テクスチャ無ければコピー
                if (AssetDatabase.AssetPathToGUID(new_path) == "")
                {
                    AssetDatabase.CopyAsset(texture_path, new_path);
                }

                add_str += "src=\"images/" + Path.ChangeExtension(Path.GetFileName(texture_path), ".png") + "\" ";
            }

            add_str += "></a-sky>\n";
            ret_str += add_str;
        }

        GameObject[] allObjects  = Resources.FindObjectsOfTypeAll <GameObject>();
        int          objects_num = allObjects.Length;
        int          process_num = 0;
        int          meshIndex   = 0;

        //オブジェクト全検索
        foreach (GameObject obj in allObjects)
        {
            process_num++;
            //プログレスバー表示
            EditorUtility.DisplayProgressBar("Progress", "Now Processing...   " + process_num + "/" + objects_num, (float)process_num / (float)objects_num);

            // ProjectにあるものならAsset Path, SceneにあるオブジェクトはそのシーンのPathが返ってくる
            string path = AssetDatabase.GetAssetOrScenePath(obj);

            // シーンのPathは拡張子が .unity
            string sceneExtension = ".unity";

            // Path.GetExtension(path) で pathの拡張子を取得
            // Equals(sceneExtension)で sceneExtensionと比較
            bool isExistInScene = Path.GetExtension(path).Equals(sceneExtension);

            // シーン内のオブジェクトかどうか判定
            if (isExistInScene)
            {
                //非表示オブジェクトならスキップ
                if (!obj.activeInHierarchy)
                {
                    continue;
                }

                MeshFilter          meshFilter          = obj.GetComponent <MeshFilter>();
                Light               light               = obj.GetComponent <Light>();
                SpriteRenderer      spriteRenderer      = obj.GetComponent <SpriteRenderer>();
                SkinnedMeshRenderer skinnedMeshRenderer = obj.GetComponent <SkinnedMeshRenderer>();

                //メッシュフィルターコンポーネントを持ってるなら
                if (meshFilter && meshFilter.sharedMesh)
                {
                    // Get the image src url string to reference in the HTML tag.
                    Material mat         = obj.GetComponent <Renderer>().sharedMaterial;
                    string   imageSrcUrl = "";
                    if (mat)
                    {
                        imageSrcUrl = "src=\"" + outputTexture(mat, meshIndex).Replace("src: ", "") + "\" ";
                    }

                    //Cubeの場合
                    if (meshFilter.sharedMesh.name == "Cube")
                    {
                        Vector3 scale = obj.transform.lossyScale;

                        //string append_str = indent + "<a-entity geometry=\"primitive: box; width: " + scale.x + "; height: " + scale.y + "; depth: " + scale.z + "\" " + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj) + "></a-entity>\n";
                        string append_str = indent + "<a-box " + (enable_physics ? "static-body " : " ") + imageSrcUrl + "geometry=\"primitive: box; width: " + scale.x + "; height: " + scale.y + "; depth: " + scale.z + "\" " + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj, meshIndex) + "></a-box>\n";
                        ret_str += append_str;
                    }
                    //Sphereの場合
                    else if (meshFilter.sharedMesh.name == "Sphere")
                    {
                        //各軸scaleが使えないので各スケールの平均値をradiusとする
                        Vector3 scale  = obj.transform.lossyScale;
                        float   radius = 0.5f;
                        if (scale != Vector3.one)
                        {
                            radius = (scale.x + scale.y + scale.z) * 0.333333333f * 0.5f;
                        }
                        //string append_str = indent + "<a-entity geometry=\"primitive: sphere; radius: " + radius + "\" " + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj) + "></a-entity>\n";
                        string append_str = indent + "<a-sphere " + (enable_physics ? "static-body " : " ") + imageSrcUrl + "geometry=\"primitive: sphere; radius: " + radius + "\" " + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj, meshIndex) + "></a-sphere>\n";
                        ret_str += append_str;
                    }
                    //Cylinderの場合(Unityのスケール1,1,1のシリンダーは半径0.5で高さ2)  TODO:パックマンみたいに欠けたシリンダー対応 独自コンポーネントくっつけて対応予定
                    else if (meshFilter.sharedMesh.name == "Cylinder")
                    {
                        //例によってスケールのxとzの平均を半径、yを高さとする
                        Vector3 scale  = obj.transform.lossyScale;
                        float   radius = 0.5f;
                        radius = (scale.x + scale.z) * 0.5f * 0.5f;
                        float height = scale.y * 2f;
                        //string append_str = indent + "<a-entity geometry=\"primitive: cylinder; radius: " + radius + "\" height:" + height + "; " + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj) + "></a-entity>\n";
                        string append_str = indent + "<a-cylinder " + (enable_physics ? "static-body " : " ") + imageSrcUrl + "geometry=\"primitive: cylinder; radius: " + radius + "\" height:" + height + "; " + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj, meshIndex) + "></a-cylinder>\n";
                        ret_str += append_str;
                    }
                    //Planeの場合(Unityのスケール1,1,1のプレーンは幅10高さ10)x90回転でa-frameと揃う
                    else if (meshFilter.sharedMesh.name == "Plane")
                    {
                        Vector3 eulerAngles = obj.transform.eulerAngles;
                        eulerAngles.x -= 90f;
                        float width  = obj.transform.lossyScale.x * 10f;
                        float height = obj.transform.lossyScale.z * 10f;

                        //string append_str = indent + "<a-entity geometry=\"primitive: plane; width:" + width + "; height:" + height + "\" " + outputRotation(eulerAngles) + outputPosition(obj) + outputMaterial(obj) + "></a-entity>\n";
                        string append_str = indent + "<a-plane " + (enable_physics ? "static-body " : " ") + imageSrcUrl + "geometry=\"primitive: plane; width:" + width + "; height:" + height + "\" " + outputRotation(eulerAngles) + outputPosition(obj) + outputMaterial(obj, meshIndex, false) + "></a-plane>\n";
                        ret_str += append_str;
                    }
                    //TODO:videoの場合
                    //TODO:curvedimageの場合
                    //TODO:videosphereの場合
                    //TODO:Coneの場合
                    //TODO:Ringの場合
                    //TODO:Torusの場合
                    //TODO:Torus Knotの場合
                    //Modelの場合
                    else
                    {
                        string objFileName = meshFilter.sharedMesh.name.Replace(":", "_") + (unique_assets ? meshIndex.ToString() : "");
                        string new_path    = export_path + "/models/" + objFileName + ".obj";
                        //obj無ければ作成
                        if (!File.Exists(Application.dataPath + "/AFrameExporter/export/models/" + objFileName + ".obj"))
                        {
                            ObjExporter.MeshToFile(meshFilter, new_path, true);
                            AssetDatabase.ImportAsset(new_path);
                            var importer = (ModelImporter)ModelImporter.GetAtPath(new_path);
                            importer.animationType = ModelImporterAnimationType.None;
                            AssetDatabase.Refresh();
                        }

                        //マテリアルからテクスチャを取り出す
                        //string append_str = indent + "<a-entity loader=\"src: url(models/" + objFileName + ".obj); format: obj\" " + outputScale(obj) + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj) + "></a-entity>\n";
                        string append_str = indent + "<a-obj-model " + (enable_physics ? "static-body" : "") + " src=\"url(models/" + objFileName + ".obj)\" loader=\"src: url(models/" + objFileName + ".obj); format: obj\" " + outputScale(obj) + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj, meshIndex) + "></a-obj-model>\n";
                        ret_str += append_str;
                    }
                }
                //skinnedMeshModelの場合
                else if (skinnedMeshRenderer && skinnedMeshRenderer.sharedMesh)
                {
                    string objFileName = skinnedMeshRenderer.sharedMesh.name.Replace(":", "_") + (unique_assets ? meshIndex.ToString() : "");
                    string new_path    = export_path + "/models/" + objFileName + ".obj";
                    //obj無ければ作成
                    if (!File.Exists(Application.dataPath + "/AFrameExporter/export/models/" + objFileName + ".obj"))
                    {
                        ObjExporter.SkinnedMeshToFile(skinnedMeshRenderer, new_path, true);
                        AssetDatabase.ImportAsset(new_path);
                        var importer = (ModelImporter)ModelImporter.GetAtPath(new_path);
                        importer.animationType = ModelImporterAnimationType.None;
                        AssetDatabase.Refresh();
                    }

                    //マテリアルからテクスチャを取り出す
                    //string append_str = indent + "<a-entity loader=\"src: url(models/" + objFileName + ".obj); format: obj\" " + outputScale(obj) + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj) + "></a-entity>\n";
                    string append_str = indent + "<a-obj-model " + (enable_physics ? "static-body" : "") + " src=\"url(models/" + objFileName + ".obj)\" loader=\"src: url(models/" + objFileName + ".obj); format: obj\" " + outputScale(obj) + outputRotation(obj) + outputPosition(obj) + outputMaterial(obj, meshIndex) + "></a-obj-model>\n";
                    ret_str += append_str;
                }
                //imageの場合 UnityはQuad シングルスプライトのみ対応
                else if (spriteRenderer && spriteRenderer.sprite && spriteRenderer.sprite.pixelsPerUnit != 0)
                {
                    Sprite sprite = spriteRenderer.sprite;
                    float  width  = sprite.rect.width / sprite.pixelsPerUnit * obj.transform.lossyScale.x;
                    float  height = sprite.rect.height / sprite.pixelsPerUnit * obj.transform.lossyScale.y;

                    //テクスチャ
                    Texture tex     = sprite.texture;
                    string  tex_str = "";
                    if (tex)
                    {
                        string texture_path = AssetDatabase.GetAssetPath(tex);
                        string new_path     = export_path + "/images/" + Path.GetFileName(texture_path);
                        //テクスチャ無ければコピー
                        if (!File.Exists(Application.dataPath + "/AFrameExporter/export/images/" + Path.GetFileName(texture_path)))
                        {
                            AssetDatabase.CopyAsset(texture_path, new_path);
                            AssetDatabase.Refresh();
                        }

                        tex_str = "src=\"images/" + Path.GetFileName(texture_path) + "\" ";
                    }

                    string append_str = indent + "<a-image " + tex_str + "width=\"" + -width + "\" height=\"" + height + "\" " + outputRotation(obj) + outputPosition(obj) + "></a-image>\n";
                    ret_str += append_str;
                }
                //MainCameraの場合
                else if (!isThereCamera && obj.tag == "MainCamera")
                {
                    string append_str = "";
                    Camera camera     = obj.GetComponent <Camera>();

                    if (camera && !enable_web)
                    {
                        append_str  = indent + "<a-entity id=\"rig\" " + outputPosition(obj) + " " + outputRotation(obj, false) + ">\n";
                        append_str += indent + indent + "<a-camera cursor-color=#" + ColorToHex(cursor_color) +
                                      " wasd-controls-enabled=" + wasd_controls_enabled.ToString().ToLower() + /*" fov=" + camera.fieldOfView + " near=" + camera.nearClipPlane + " far=" + camera.farClipPlane +*/
                                      " cursor-maxdistance=" + cursor_maxdistance + " cursor-offset=" + cursor_offset + " cursor-opacity=" + cursor_opacity + " cursor-scale=" + cursor_scale +
                                      " look-controls-enabled=" + look_controls_enabled.ToString().ToLower() + "></a-camera>\n";
                        append_str += indent + "</a-entity>\n";
                    }
                    else
                    {
                        append_str  = indent + "<a-entity id=\"rig\" position=\"8.88 3.26 -16.53\" rotation=\"0 98.6636581420898 0\" movement-controls kinematic-body>\n";
                        append_str += indent + indent + "<a-entity camera look-controls tilt-controls></a-entity>\n";
                        append_str += indent + "</a-entity>\n";
                    }

                    ret_str      += append_str;
                    isThereCamera = true;
                }
                //Lightの場合
                else if (light)
                {
                    //Vector3 forward = -obj.transform.forward;

                    //Vector3 rotation = obj.transform.eulerAngles;
                    //rotation.x -= 90f;

                    SerializedObject   serializedObject    = new UnityEditor.SerializedObject(obj.transform);
                    SerializedProperty serializedEulerHint = serializedObject.FindProperty("m_LocalEulerAnglesHint");
                    Vector3            rotation            = serializedEulerHint.vector3Value;

                    //string lightPosition_str = "position=\"" + -forward.x + " " + forward.y + " " + forward.z + "\" ";
                    string lightRotation_str = "rotation=\"" + -rotation.x + " " + rotation.y + " " + rotation.z + "\" ";

                    //DirectionalLightの場合
                    if (light.type == LightType.Directional)
                    {
                        //string append_str = indent + "<a-light type=directional; intensity=" + light.intensity + " color=#" + ColorToHex(light.color) + " " + lightPosition_str + "></a-light>\n";
                        string append_str = indent + "<a-light type=directional intensity=" + light.intensity + " color=#" + ColorToHex(light.color) + " " + outputPosition(obj) + " " + lightRotation_str + "></a-light>\n";
                        ret_str     += append_str;
                        isThereLight = true;
                    }
                    else if (light.type == LightType.Point)
                    {
                        //string append_str = indent + "<a-light type=directional; intensity=" + light.intensity + " color=#" + ColorToHex(light.color) + " " + lightPosition_str + "></a-light>\n";
                        string append_str = indent + "<a-light type=point distance=" + light.range + " intensity=" + light.intensity + " color=#" + ColorToHex(light.color) + " " + outputPosition(obj) + " " + lightRotation_str + "></a-light>\n";
                        ret_str     += append_str;
                        isThereLight = true;
                    }
                    else if (light.type == LightType.Spot)
                    {
                        //string append_str = indent + "<a-light type=directional; intensity=" + light.intensity + " color=#" + ColorToHex(light.color) + " " + lightPosition_str + "></a-light>\n";
                        string append_str = indent + "<a-light type=spot distance=" + light.range + " angle=" + light.spotAngle + " intensity=" + light.intensity + " color=#" + ColorToHex(light.color) + " " + outputPosition(obj) + " " + lightRotation_str + "></a-light>\n";
                        ret_str     += append_str;
                        isThereLight = true;
                    }
                    //TODO:PointLightの場合
                    //TODO:SpotLightの場合
                    //TODO:AmbientLightの場合
                    //TODO:Hemisphereの場合
                }
            }

            meshIndex++;
        }

        //Cameraが無い場合はデフォルト設定
        if (!isThereCamera)
        {
            string append_str = "";
            if (!enable_web)
            {
                append_str = indent + "<a-camera cursor-color=#" + ColorToHex(cursor_color) +
                             " wasd-controls-enabled=" + wasd_controls_enabled.ToString().ToLower() + "></a-camera>\n";
            }
            else
            {
                append_str  = indent + "<a-entity id=\"rig\" position=\"8.88 3.26 -16.53\" rotation=\"0 98.6636581420898 0\" movement-controls kinematic-body>\n";
                append_str += indent + indent + "<a-entity camera look-controls tilt-controls></a-entity>\n";
                append_str += indent + "</a-entity>\n";
            }

            ret_str      += append_str;
            isThereCamera = true;
        }

        //Lightが無い場合はデフォルトライト
        if (!isThereLight)
        {
        }

        EditorUtility.ClearProgressBar();

        return(ret_str);
    }
Exemplo n.º 3
0
        /**
         * @Return true if this GameObject lives in the Scene.  False if it's part of an asset.
         */
        public static bool EditorIsSceneObject(this GameObject gameObj)
        {
            string assetPath = AssetDatabase.GetAssetOrScenePath(gameObj);

            return(!EditorUtility.IsPersistent(gameObj) || assetPath.EndsWith(".unity"));
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public override bool ValidateAsset(Object obj)
        {
            var path = AssetDatabase.GetAssetOrScenePath(obj);

            return(ValidateAsset(path));
        }
Exemplo n.º 5
0
        private void DisplayLoaderSelectionUI()
        {
            BuildTargetGroup buildTargetGroup = EditorGUILayout.BeginBuildTargetSelectionGrouping();

            try
            {
                bool buildTargetChanged = m_LastBuildTargetGroup != buildTargetGroup;
                if (buildTargetChanged)
                {
                    m_LastBuildTargetGroup = buildTargetGroup;
                }

                XRGeneralSettings settings = currentSettings.SettingsForBuildTarget(buildTargetGroup);
                if (settings == null)
                {
                    settings = ScriptableObject.CreateInstance <XRGeneralSettings>() as XRGeneralSettings;
                    currentSettings.SetSettingsForBuildTarget(buildTargetGroup, settings);
                    settings.name = $"{buildTargetGroup.ToString()} Settings";
                    AssetDatabase.AddObjectToAsset(settings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                }

                var serializedSettingsObject = new SerializedObject(settings);
                serializedSettingsObject.Update();

                SerializedProperty initOnStart = serializedSettingsObject.FindProperty("m_InitManagerOnStart");
                EditorGUILayout.PropertyField(initOnStart, Content.k_InitializeOnStart);
                EditorGUILayout.Space();

                SerializedProperty loaderProp = serializedSettingsObject.FindProperty("m_LoaderManagerInstance");

                if (!CachedSettingsEditor.ContainsKey(buildTargetGroup))
                {
                    CachedSettingsEditor.Add(buildTargetGroup, null);
                }

                if (loaderProp.objectReferenceValue == null)
                {
                    var xrManagerSettings = ScriptableObject.CreateInstance <XRManagerSettings>() as XRManagerSettings;
                    xrManagerSettings.name = $"{buildTargetGroup.ToString()} Providers";
                    AssetDatabase.AddObjectToAsset(xrManagerSettings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                    loaderProp.objectReferenceValue = xrManagerSettings;
                    serializedSettingsObject.ApplyModifiedProperties();
                }

                var obj = loaderProp.objectReferenceValue;

                if (obj != null)
                {
                    loaderProp.objectReferenceValue = obj;

                    if (CachedSettingsEditor[buildTargetGroup] == null)
                    {
                        CachedSettingsEditor[buildTargetGroup] = Editor.CreateEditor(obj) as XRManagerSettingsEditor;

                        if (CachedSettingsEditor[buildTargetGroup] == null)
                        {
                            Debug.LogError("Failed to create a view for XR Manager Settings Instance");
                        }
                    }

                    if (CachedSettingsEditor[buildTargetGroup] != null)
                    {
                        if (ResetUi)
                        {
                            ResetUi = false;
                            CachedSettingsEditor[buildTargetGroup].Reload();
                        }

                        CachedSettingsEditor[buildTargetGroup].BuildTarget = buildTargetGroup;
                        CachedSettingsEditor[buildTargetGroup].OnInspectorGUI();
                    }
                }
                else if (obj == null)
                {
                    settings.AssignedSettings       = null;
                    loaderProp.objectReferenceValue = null;
                }

                serializedSettingsObject.ApplyModifiedProperties();
            }
            catch (Exception ex)
            {
                Debug.LogError($"Error trying to display plug-in assingment UI : {ex.Message}");
            }

            EditorGUILayout.EndBuildTargetSelectionGrouping();
        }
Exemplo n.º 6
0
 private static bool IsInBuildSettings(Object newScene)
 {
     return(newScene && EditorBuildSettings.scenes.Any(s => s.path == AssetDatabase.GetAssetOrScenePath(newScene)));
 }
Exemplo n.º 7
0
    static void BuildSceneMenu()
    {
        var selectedObjects = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets);
        if (selectedObjects != null && selectedObjects.Length == 1)
        {
            string[] scenes = new string[1];
            scenes[0] = AssetDatabase.GetAssetOrScenePath(selectedObjects[0]);
            if (!scenes[0].Contains(".unity"))
            {
                Debug.LogWarning("You did not choose a scene file to buid");
                return;
            }

            string path;
            string ext = "";
            switch (EditorUserBuildSettings.activeBuildTarget)
            {
                case BuildTarget.Android:
                    ext = "apk";
                    break;
                case BuildTarget.StandaloneWindows:
                    ext = "exe";
                    break;
                case BuildTarget.StandaloneOSX:
                    ext = "app";
                    break;
                default:
                    break;
            }
            if (EditorPrefs.HasKey(scenes[0]))
            {
                path = EditorPrefs.GetString(scenes[0]);
            }
            else
            {
                path = Application.dataPath;
            }
            path = EditorUtility.SaveFilePanel("Build file", Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + "." + ext, ext);
            if (!string.IsNullOrEmpty(path))
            {
                EditorPrefs.SetString(scenes[0], Path.GetFullPath(path));
                if (EditorBuildSettings.scenes.Length > 0)
                {
                    var first = EditorBuildSettings.scenes[0];
                    var newone = new EditorBuildSettingsScene(path, true);
                    EditorBuildSettings.scenes[0] = newone;
                    BuildPipeline.BuildPlayer(scenes, path, EditorUserBuildSettings.activeBuildTarget, BuildOptions.ShowBuiltPlayer);
                    EditorBuildSettings.scenes[0] = first;
                }
                else
                {
                    var tempScenes = new EditorBuildSettingsScene[1];
                    var newone = new EditorBuildSettingsScene(path, true);
                    tempScenes[0] = newone;
                    EditorBuildSettings.scenes = tempScenes;
                    BuildPipeline.BuildPlayer(scenes, path, EditorUserBuildSettings.activeBuildTarget, BuildOptions.ShowBuiltPlayer);
                    EditorBuildSettings.scenes = null;
                }
            }

        }
    }
Exemplo n.º 8
0
    private void Make()
    {
        string path = AssetDatabase.GetAssetOrScenePath(png_folder);

        string[] sp_path  = path.Split('/');
        string   con_path = "";
        string   mat_path = "";

        for (int i = 0; i < sp_path.Length - 2; i++)
        {
            con_path += (sp_path[i] + "/");
        }
        con_path += (sp_path[sp_path.Length - 2]);

        AssetDatabase.CreateFolder(con_path, "material");
        for (int i = 0; i < sp_path.Length - 1; i++)
        {
            mat_path += (sp_path[i] + "/");
        }
        mat_path += (sp_path[sp_path.Length - 1] + "/" + sp_path[sp_path.Length - 2]); //ここのフォルダ名を入れられたフォルダ名から取得に変更する
        for (int i = 0; ; i++)
        {
            string mat_path_p = "-";

            if (i < 9)
            {
                mat_path_p += "00" + (i + 1);
            }
            else if (i < 99)
            {
                mat_path_p += "0" + (i + 1);
            }
            else if (i < 999)
            {
                mat_path_p += (i + 1);
            }
            else
            {
                Debug.Log("999までじゃ");
                return;
            }

            Debug.Log(mat_path + mat_path_p);
            if (File.Exists(mat_path + mat_path_p + ".png"))
            {
                mat_path_p += ".png";
                Debug.Log("pngあるで");
            }
            else if (File.Exists(mat_path + mat_path_p + ".jpg"))
            {
                mat_path_p += ".jpg";
                Debug.Log("jpgあるで");
            }
            else
            {
                Debug.Log("ないで");
                mat_path_p = "-";
                if (i < 9)
                {
                    mat_path_p += "0" + (i + 1);
                }
                else if (i < 99)
                {
                    mat_path_p += (i + 1);
                }
                else
                {
                    Debug.Log("99までじゃ");
                    return;
                }
                //mat_path_p += ".png";

                Debug.Log(mat_path + mat_path_p);
                if (File.Exists(mat_path + mat_path_p + ".png"))
                {
                    mat_path_p += ".png";
                    Debug.Log("pngあるで");
                }
                else if (File.Exists(mat_path + mat_path_p + ".jpg"))
                {
                    mat_path_p += ".jpg";
                    Debug.Log("jpgあるで");
                }
                else
                {
                    Debug.Log("ないで");
                    mat_path_p = "-";

                    if (i < 9)
                    {
                        mat_path_p += (i + 1);
                    }
                    else
                    {
                        Debug.Log("9までじゃ");
                        return;
                    }

                    Debug.Log(mat_path + mat_path_p);
                    if (File.Exists(mat_path + mat_path_p + ".png"))
                    {
                        mat_path_p += ".png";
                        Debug.Log("あるで");
                    }
                    else if (File.Exists(mat_path + mat_path_p + ".jpg"))
                    {
                        mat_path_p += ".jpg";
                        Debug.Log("jpgあるで");
                    }
                    else
                    {
                        Debug.Log("ないで");
                        break;
                    }
                }
            }
            Debug.Log(mat_path + mat_path_p);

            Texture2D texture = AssetDatabase.LoadAssetAtPath(mat_path + mat_path_p, typeof(Texture2D)) as Texture2D;


            Material mat = new Material(Shader.Find("Unlit/Texture"));
            if (mat_sample != null)
            {
                mat.shader = mat_sample.shader;
                mat.CopyPropertiesFromMaterial(mat_sample);
            }
            mat.SetTexture("_MainTex", texture);
            Debug.Log((con_path + "/material/p" + i + sp_path[sp_path.Length - 2] + ".mat"));
            AssetDatabase.CreateAsset(mat, (con_path + "/material/p" + i + sp_path[sp_path.Length - 2] + ".mat"));
        }
    }
Exemplo n.º 9
0
        // JSON SERIALIZATION
        public static string ParametricObjectAsJSON(AXParametricObject po)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("{");

            sb.Append(" \"basedOnAssetWithGUID\":\"" + po.basedOnAssetWithGUID + "\"");
            sb.Append(",\"author\":\"" + po.author + "\"");
            sb.Append(",\"tags\":\"" + po.tags + "\"");

            sb.Append(",\"guid\":\"" + po.Guid + "\"");
            sb.Append(", \"name\":\"" + po.Name + "\"");
            sb.Append(", \"description\":\"" + po.description + "\"");
            sb.Append(", \"type\":\"" + po.Type + "\"");
            sb.Append(", \"isInitialized\":\"" + po.isInitialized + "\"");
            sb.Append(", \"documentationURL\":\"" + po.documentationURL + "\"");


            sb.Append(", \"includeInSidebarMenu\":\"" + po.includeInSidebarMenu + "\"");


            sb.Append(",\"grouperKey\":\"" + po.grouperKey + "\"");



            sb.Append(", \"rect\":" + AXJson.RectToJSON(po.rect));
            sb.Append(", \"bounds\":" + AXJson.BoundsToJSON(po.bounds));
            sb.Append(", \"transMatrix\":" + AXJson.Matrix4x4ToJSON(po.transMatrix));

            if (po.curve != null && po.curve.Count > 0)
            {
                sb.Append(", \"curve\":" + AXJson.CurveToJson(po.curve));
            }

            sb.Append(", \"sortval\":\"" + po.sortval + "\"");

            sb.Append(", \"combineMeshes\":\"" + po.combineMeshes + "\"");
            sb.Append(", \"isRigidbody\":\"" + po.isRigidbody + "\"");
            sb.Append(", \"colliderType\":\"" + po.colliderType.GetHashCode() + "\"");

            sb.Append(", \"axStaticEditorFlags\":\"" + po.axStaticEditorFlags.GetHashCode() + "\"");



            // material
            //Debug.Log ("ENCODE MATERIAL::::");
                        #if UNITY_EDITOR
            if (po.axMat != null && po.axMat.mat != null)
            {
                string matPath = AssetDatabase.GetAssetOrScenePath(po.axMat.mat);
                if (!String.IsNullOrEmpty(matPath))
                {
                    sb.Append(", \"material_assetGUID\":\"" + AssetDatabase.AssetPathToGUID(matPath) + "\"");
                }
            }
                        #endif

            // code
            if (po.code != null)
            {
                sb.Append(", \"code\":\"" + po.code.Replace("\n", ";") + "\"");
            }



            // parameters
            sb.Append(", \"parameters\": [");                           // begin parameters
            string the_comma = "";
            foreach (AXParameter p in po.parameters)
            {
                sb.Append(the_comma + p.asJSON());
                the_comma = ", ";
            }
            sb.Append("]");                                                             // end parameters

            // shapes
            if (po.shapes != null)
            {
                sb.Append(", \"shapes\": [");                           // begin parameters
                the_comma = "";
                foreach (AXShape shp in po.shapes)
                {
                    sb.Append(the_comma + shp.asJSON());
                    the_comma = ", ";
                }
                sb.Append("]");                                                                 // end parameters
            }

            // handles

            if (po.handles != null && po.handles.Count > 0)
            {
                sb.Append(", \"handles\": [");                          // begin parameters
                the_comma = "";
                foreach (AXHandle h in po.handles)
                {
                    sb.Append(the_comma + h.asJSON());
                    the_comma = ", ";
                }
                sb.Append("]");
            }            // end parameters


            // cameraSettings
            if (po.cameraSettings != null)
            {
                sb.Append(",\"cameraSettings\":" + JSONSerializersAX.AXCameraAsJSON(po.cameraSettings));
            }



            // finish
            sb.Append("}");             // end parametri_object
            //Debug.Log (sb.ToString());
            return(sb.ToString());
        }
Exemplo n.º 10
0
        public void SetTextureSize(Texture2D tx, int size)
        {
            TextureImporter ai = AssetImporter.GetAtPath(AssetDatabase.GetAssetOrScenePath(tx)) as TextureImporter;

            if (ai == null)
            {
                return;
            }

            int maxSize = 32;

            if (size > 32)
            {
                maxSize = 64;
            }
            if (size > 64)
            {
                maxSize = 128;
            }
            if (size > 128)
            {
                maxSize = 256;
            }
            if (size > 256)
            {
                maxSize = 512;
            }
            if (size > 512)
            {
                maxSize = 1024;
            }
            if (size > 1024)
            {
                maxSize = 2048;
            }
            if (size > 2048)
            {
                maxSize = 4096;
            }

            bool isSettingsChanged = false;

            if (ai.maxTextureSize != maxSize)
            {
                ai.maxTextureSize = maxSize;
                isSettingsChanged = true;
            }

#if UNITY_5_5_OR_NEWER
            string[] platforms = { "Standalone", "Web", "iPhone", "Android", "WebGL", "Windows Store Apps", "PSP2", "PS4", "XboxOne", "Nintendo 3DS", "tvOS" };
            foreach (string platform in platforms)
            {
                TextureImporterPlatformSettings settings = ai.GetPlatformTextureSettings(platform);
                if (settings != null && settings.overridden && settings.maxTextureSize != maxSize)
                {
                    settings.maxTextureSize = maxSize;
                    ai.SetPlatformTextureSettings(settings);
                    isSettingsChanged = true;
                }
            }

            // reimport if anything changed
            if (isSettingsChanged)
            {
                ai.SaveAndReimport();
            }
#else
            if (ai.maxTextureSize != maxSize)
            {
                ai.maxTextureSize = maxSize;
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetOrScenePath(tx), ImportAssetOptions.ForceUpdate);
            }
#endif
        }
        public override void OnGUI(string searchContext)
        {
            if (m_SettingsWrapper != null && m_SettingsWrapper.targetObject != null)
            {
                m_SettingsWrapper.Update();

                BuildTargetGroup buildTargetGroup = EditorGUILayout.BeginBuildTargetSelectionGrouping();

                XRGeneralSettings settings = currentSettings.SettingsForBuildTarget(buildTargetGroup);
                if (settings == null)
                {
                    settings = ScriptableObject.CreateInstance <XRGeneralSettings>() as XRGeneralSettings;
                    currentSettings.SetSettingsForBuildTarget(buildTargetGroup, settings);
                    AssetDatabase.AddObjectToAsset(settings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                }

                var serializedSettingsObject = new SerializedObject(settings);
                serializedSettingsObject.Update();

                SerializedProperty initOnStart = serializedSettingsObject.FindProperty("m_InitManagerOnStart");
                EditorGUILayout.PropertyField(initOnStart, s_LoaderInitOnStartLabel);

                SerializedProperty loaderProp = serializedSettingsObject.FindProperty("m_LoaderManagerInstance");

                if (!CachedSettingsEditor.ContainsKey(buildTargetGroup))
                {
                    CachedSettingsEditor.Add(buildTargetGroup, null);
                }

                if (loaderProp.objectReferenceValue == null)
                {
                    var xrManagerSettings = ScriptableObject.CreateInstance <XRManagerSettings>() as XRManagerSettings;
                    AssetDatabase.AddObjectToAsset(xrManagerSettings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                    loaderProp.objectReferenceValue = xrManagerSettings;
                    serializedSettingsObject.ApplyModifiedProperties();
                }

                EditorGUI.BeginChangeCheck();
                var obj = EditorGUILayout.ObjectField(s_LoaderXRManagerLabel, loaderProp.objectReferenceValue, typeof(XRManagerSettings), false) as XRManagerSettings;

                if (EditorGUI.EndChangeCheck())
                {
                    CachedSettingsEditor[buildTargetGroup] = null;
                }

                if (obj != null)
                {
                    loaderProp.objectReferenceValue = obj;

                    if (CachedSettingsEditor[buildTargetGroup] == null)
                    {
                        CachedSettingsEditor[buildTargetGroup] = Editor.CreateEditor(obj);

                        if (CachedSettingsEditor[buildTargetGroup] == null)
                        {
                            Debug.LogError("Failed to create a view for XR Settings Instance");
                        }
                    }

                    if (CachedSettingsEditor[buildTargetGroup] != null)
                    {
                        CachedSettingsEditor[buildTargetGroup].OnInspectorGUI();
                    }
                }
                else if (obj != null)
                {
                    Debug.LogError("The chosen prefab is missing an instance of the XRManager component.");
                }
                else if (obj == null)
                {
                    settings.AssignedSettings       = null;
                    loaderProp.objectReferenceValue = null;
                }

                serializedSettingsObject.ApplyModifiedProperties();

                EditorGUILayout.EndBuildTargetSelectionGrouping();

                m_SettingsWrapper.ApplyModifiedProperties();
            }

            base.OnGUI(searchContext);
        }
Exemplo n.º 12
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            TerrainExtension ter = (TerrainExtension)target as TerrainExtension;

            EditorGUILayout.Separator();
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Editor for terrain extension");
            EditorGUILayout.EndHorizontal();

            /*if (ter.Lightmap != null)
             * {
             *  if (GUILayout.Button("Generate NormalMap"))
             *  {
             *      if (ter.BakeAllTimeIndicesUpTo > 0)
             *      {
             *          for (int i = 0; i < ter.BakeAllTimeIndicesUpTo; i++)
             *          {
             *              ter.BakeTimeIndex = i;
             *              TerrainMapGenerator.GenerateNormalMap(ter, AssetDatabase.GetAssetOrScenePath(ter.GetNormalMap()));
             *          }
             *      }
             *      else
             *      {
             *          TerrainMapGenerator.GenerateNormalMap(ter, AssetDatabase.GetAssetOrScenePath(ter.GetNormalMap()));
             *      }
             *  }
             *
             *  if (GUILayout.Button("Generate HeightMap"))
             *  {
             *      TerrainMapGenerator.GenerateHeightMap(ter, AssetDatabase.GetAssetOrScenePath(ter.GetHeightMap()));
             *  }
             *
             * }
             * else
             * {
             *  GUILayout.Label("Must create a png map (with correct settings)\n and associate it as Normal map on both the material\n and on the terrain extension");
             * }*/


            if (ter.GetSplatMap() != null)
            {
                if (GUILayout.Button("Set splat from map"))
                {
                    SetSplatFromMap(ter);
                }

                if (GUILayout.Button("Save splatmap"))
                {
                    TerrainMapGenerator.SaveSplatMapFromTerrain(ter, AssetDatabase.GetAssetOrScenePath(ter.GetSplatMap()));
                }
            }

            if (GUILayout.Button("Generate splatmap from terrain"))
            {
                TerrainMapGenerator.GenerateSplatMap(ter);
            }

            if (GUILayout.Button("Smooth terrain"))
            {
                SmoothTerrain(ter);
            }

            /*if (GUILayout.Button("AddRockNoise"))
             * {
             *  TerrainMapGenerator.GenerateRockNoise(ter);
             * }*/
        }
 /// <summary>
 /// 将旧的ModName换成新的ModName
 /// </summary>
 static void ChangeModName(string NewModName, UnityEngine.Object asset)
 {
     AssetDatabase.RenameAsset(AssetDatabase.GetAssetOrScenePath(asset), asset.GetAssetNameEditor() + NewModName);
 }
Exemplo n.º 14
0
    //    [MenuItem("Assets/===CreateBundle===", false, 10)]
    static void CreateSelectedBundle()
    {
        UnityEngine.Object[] arr = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets);
        string path = AssetDatabase.GetAssetOrScenePath(arr[0]);

        FileInfo fileInfo = new FileInfo(path);

        List <AssetBundleBuild> bundleList = new List <AssetBundleBuild>();

        int count = 0;

        if (fileInfo.Attributes == FileAttributes.Directory)
        {
            string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                if (file.LastIndexOf(".meta", StringComparison.Ordinal) != -1)
                {
                    continue;
                }

                string filePath = file.Replace("\\", "/");

                AssetBundleBuild bundle = new AssetBundleBuild();
                if (filePath.StartsWith(SingleFilePath))
                {
                    bundle = CreateSingleFile(filePath);
                }
                else if (filePath.StartsWith(ModulePath))
                {
                    bundle = CreateModule(filePath);
                }
                else if (filePath.StartsWith(AudioPath))
                {
                    bundle = CreateAudio(filePath);
                }
                else if (filePath.StartsWith(UiSpriteAtlasPath))
                {
                    if (filePath.EndsWith(".spriteatlas") == false)
                    {
                        continue;
                    }
                    bundle = CreateUiAtlas(filePath);
                }
                else if (filePath.StartsWith(StoryPath))
                {
                    bundle = CreateStory(filePath);
                }

                if (string.IsNullOrEmpty(bundle.assetBundleName))
                {
                    continue;
                }

                bundleList.Add(bundle);
            }
        }

        CheckAndCreateDir(GetBundleOutputPath());


//        AssetBundleManifest manifest =
//            BuildPipeline.BuildAssetBundles(GetBundleOutputPath(), bundleList.ToArray(), BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);
    }
Exemplo n.º 15
0
 private void OpenFlyingIslesExampleScene()
 {
     UnityEditor.SceneManagement.EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(_exampleFlyingIsles));
 }
Exemplo n.º 16
0
        /// <summary>
        /// Destroys loose preset objects that live in memory and not in assets
        /// </summary>
        public static void CleanupPresetsOfType <T>() where T : PumkinPreset
        {
            var tools = PumkinsAvatarTools.Instance;

            foreach (var p in GameObject.FindObjectsOfType <T>())
            {
                if (p && string.IsNullOrEmpty(AssetDatabase.GetAssetPath(p)))
                {
                    Debug.Log("Destroying orphanned " + typeof(T).Name);
                    GameObject.DestroyImmediate(p);
                }
            }

            if (typeof(T) == typeof(PumkinsCameraPreset))
            {
                CameraPresets.RemoveAll(o => o == default(PumkinsCameraPreset) || string.IsNullOrEmpty(AssetDatabase.GetAssetPath(o)) || string.IsNullOrEmpty(o.name));
            }
            else if (typeof(T) == typeof(PumkinsPosePreset))
            {
                PosePresets.RemoveAll(o => o == default(PumkinsPosePreset) || string.IsNullOrEmpty(AssetDatabase.GetAssetOrScenePath(o)) || string.IsNullOrEmpty(o.name));
            }
            else if (typeof(T) == typeof(PumkinsBlendshapePreset))
            {
                BlendshapePresets.RemoveAll(o => o == default(PumkinsBlendshapePreset) || string.IsNullOrEmpty(AssetDatabase.GetAssetOrScenePath(o)) || string.IsNullOrEmpty(o.name));
            }

            PumkinsAvatarTools.RefreshPresetIndex <T>();
        }
Exemplo n.º 17
0
    // moho fbx import後に通過する処理
    void OnPostprocessModel(GameObject g)
    {
        // Only operate on FBX files
        if (assetPath.IndexOf(".fbx") == -1)
        {
            return;
        }

        if (!isMohoModel)
        {
            //Debug.Log("*** Not Moho ***");
            return;
        }

        //AnimationControllerを作成
        var filePath = System.IO.Path.GetDirectoryName(assetPath);

        filePath = filePath + "/" + g.name + "_Controller.controller";

        AnimatorController animCont = null;
        var asset = AssetDatabase.LoadAssetAtPath(filePath, typeof(AnimatorController)) as AnimatorController;

        if (asset == null)
        {
            animCont = AnimatorController.CreateAnimatorControllerAtPath(filePath);
            AssetDatabase.Refresh();
        }
        else
        {
            animCont = asset;
        }

        //いったん作ったAnimatorControllerのリンクを破棄してAssetDatabaseから読み込みしなおし
        //animCont = null;
        //animCont = AssetDatabase.LoadAssetAtPath(filePath, typeof(AnimatorController)) as AnimatorController;

        //TODO:AnimationClipをSteteにセットしたいがNullになる未調査

        /*{
         *  Debug.Log("AnimationClip Path>>" + ClipPath);
         *  AnimationClip tempClip = AssetDatabase.LoadAssetAtPath(ClipPath, typeof(AnimationClip)) as AnimationClip;
         *  var makeStateMachine = animCont.layers[0].stateMachine;
         *  Debug.Log(makeStateMachine + "/" + animCont + "/[" + tempClip.name + "]");
         *  var animState = makeStateMachine.AddState("DefaultMotion");
         *  animState.motion = tempClip;
         * }*/

        //Animatorはつけておきます
        Animator gAnim = g.AddComponent <Animator>();

        gAnim.runtimeAnimatorController = animCont;

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        Shader shader = Shader.Find("Moho/TransparentShader");

        if (shader == null)
        {
            return;
        }

        Renderer[] renderers           = g.GetComponentsInChildren <Renderer>();
        int        straightRenderOrder = 0;// shader.renderQueue;

        foreach (Renderer r in renderers)
        {
            int renderOrder = straightRenderOrder;
            if (r.name.Contains("|"))
            {
                string[] stringSeparators = new string[] { "|" };
                string[] parts            = r.name.Split(stringSeparators, StringSplitOptions.None);
                int      j;
                if (Int32.TryParse(parts[parts.Length - 1], out j))
                {
                    renderOrder += j;
                }
            }
            r.sharedMaterial.shader = shader; // apply an unlit shader
            //r.sharedMaterial.renderQueue = renderOrder; // set a fixed render order
            r.sharedMaterial.SetFloat("_CullMode", (float)UnityEngine.Rendering.CullMode.Off);
            r.sharedMaterial.SetFloat("_ZWrite", 0f);
            r.sharedMaterial.SetFloat("_OffsetFactor", -1f * renderOrder);
            r.sharedMaterial.SetFloat("_OffsetUnits", -1f * renderOrder);
            //straightRenderOrder++;


            Texture tex = r.sharedMaterial.GetTexture("_MainTex");
            if (tex == null)
            {
                Debug.LogError("r.sharedMaterial.GetTexture(_MainTex) が見つからなかった r:" + r);
                continue;
            }
            string          texPath = AssetDatabase.GetAssetPath(tex);
            TextureImporter _ti     = AssetImporter.GetAtPath(texPath) as TextureImporter;
            _ti.mipmapEnabled = false;
            _ti.wrapMode      = TextureWrapMode.Clamp;

            EditorUtility.SetDirty(_ti);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            AssetDatabase.ImportAsset(texPath, ImportAssetOptions.ForceUpdate);
        }

        //Import時に変なScaleが入っていた時はScale1に戻す
        //必要なら、Animationの方にScaleが入っているからこちらは見えるようにします
        Transform[] transforms = g.GetComponentsInChildren <Transform>();
        foreach (Transform T in transforms)
        {
            if (T.localScale.x < 0.00001f && T.localScale.y < 0.00001f && T.localScale.z < 0.00001f)
            {
                T.localScale = Vector3.one;
            }
        }

        Debug.Log("moho import処理完了待ち開始 assetPath:" + assetPath);// Assets/somewhere/x.fbx

        // 上で作成したいろいろなものがAssetDatabaseにセットされるので、その完了待ちをする。完了時処理とかもしこめる。
        var importedPathSource = assetPath.Split('/');
        var importedPathSourceWithoutFileName = new string[importedPathSource.Length - 1];

        for (var i = 0; i < importedPathSourceWithoutFileName.Length; i++)
        {
            importedPathSourceWithoutFileName[i] = importedPathSource[i];
        }
        var importedPath = string.Join("/", importedPathSourceWithoutFileName);

        // この時点で9ファイルある、これが10ファイルになる
        var fileCount = Directory.GetFiles(importedPath).Length;

        IEnumerator waitCor()
        {
            // assetImport処理が終わるまで待つ
            while (true)
            {
                var filePaths = Directory.GetFiles(importedPath);
                // foreach (var f in filePaths)
                // {
                //     Debug.Log("f:" + f);
                // }

                // TODO: 今のところは1ファイルでも増えてれば完了にしてる
                if (fileCount < filePaths.Length)
                {
                    break;
                }
                yield return(null);
            }


            var targetFBX = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;

            var FBXPath     = AssetDatabase.GetAssetPath(targetFBX);
            var path        = Path.GetDirectoryName(AssetDatabase.GetAssetOrScenePath(targetFBX));
            var projectName = Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetOrScenePath(targetFBX));

            var animFilePath = path + "/" + projectName + "_anim/Mainline.anim";
            var jsonFilePath = path + "/" + projectName + ".json";

            var animData = AssetDatabase.LoadAssetAtPath(animFilePath, typeof(AnimationClip)) as AnimationClip;

            if (File.Exists(jsonFilePath) || animData != null)
            {
                var jsonData = File.ReadAllText(jsonFilePath);
                MohoSmartWarpImporter.Run(projectName, FBXPath, targetFBX, jsonData, path, animData);
            }
            else
            {
                //animファイルか、Jsonファイルがありません
                Debug.LogError("情報が足りていません、以下を確認ください");
                Debug.LogError("FBXをReimportする");
                Debug.LogError("jsonファイルを作成する");
            }

            Debug.Log("import処理完了 assetPath:" + assetPath);
        };
        EditorCoroutine.StartEditorCoroutine(waitCor());
    }
Exemplo n.º 18
0
        // returns true if the element should be removed
        private bool DrawElement(ObjectReference reference)
        {
            if (reference == null)
            {
                return(true);
            }

            var drawData  = reference.GetProvidedData();
            var sceneData = drawData.SceneData;

            float inspectorWidth = EditorGUIUtility.currentViewWidth;
            float buttonWidth    = inspectorWidth + BORDER_SPACE;

            buttonWidth = sceneData.IsScene ? (buttonWidth / 3) - 2.5f : buttonWidth;

            GUILayout.BeginHorizontal();

#if UNITY_5_4_OR_NEWER
            GUILayout.Label(drawData.Icon, GUILayout.Width(ICON_SIZE), GUILayout.Height(ICON_SIZE), GUILayout.MaxWidth(ICON_SIZE), GUILayout.MaxHeight(ICON_SIZE));
#else
            buttonWidth += ICON_SIZE + 10;
#endif

            if (GUILayout.Button(drawData.Name, GUILayout.MaxWidth(buttonWidth), GUILayout.Width(buttonWidth), GUILayout.ExpandWidth(false)))
            {
                reference.UpdateCachedData();
                reference.Select();
            }

#if UNITY_5_4_OR_NEWER
            if (sceneData.IsScene)
            {
                var scene = sceneData.Scene;
                // Playmode
                if (Application.isPlaying)
                {
                    if (GUILayout.Button("Load", GUILayout.MaxWidth(buttonWidth * 2 + 2.5f), GUILayout.Width(buttonWidth * 2 + 2.5f), GUILayout.ExpandWidth(false)))
                    {
                        SceneManager.LoadScene(AssetDatabase.GetAssetOrScenePath(scene));
                    }
                }
                else
                {
                    if (GUILayout.Button("Load", GUILayout.MaxWidth(buttonWidth), GUILayout.Width(buttonWidth), GUILayout.ExpandWidth(false)))
                    {
                        if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                        {
                            EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(scene), OpenSceneMode.Single);
                        }
                    }

                    if (GUILayout.Button("Play", GUILayout.MaxWidth(buttonWidth), GUILayout.Width(buttonWidth), GUILayout.ExpandWidth(false)))
                    {
                        if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                        {
                            EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(scene), OpenSceneMode.Single);
                        }
                        EditorApplication.isPlaying = true;
                    }
                }
            }
#endif

            var alignmentBckp = GUIStyle.none.alignment;
            GUIStyle.none.alignment = TextAnchor.LowerCenter;
            if (GUILayout.Button(CLOSE_ICON, GUIStyle.none, GUILayout.Width(ICON_SIZE), GUILayout.Height(ICON_SIZE)))
            {
                return(true);
            }

            GUIStyle.none.alignment = alignmentBckp;
            GUILayout.EndHorizontal();
            GUILayout.Space(5);
            return(false);
        }
Exemplo n.º 19
0
        public override void Draw(int aID)
        {
            if (dataControlList.index != -1)
            {
                var unitySceneDataControl = dataControlList.list[dataControlList.index] as UnitySceneDataControl;

                EditorGUI.BeginChangeCheck();
                var scene    = AssetDatabase.LoadAssetAtPath <SceneAsset>(unitySceneDataControl.Scene);
                var newScene = EditorGUILayout.ObjectField("Scene", scene, typeof(SceneAsset), true);
                if (EditorGUI.EndChangeCheck())
                {
                    unitySceneDataControl.Scene = AssetDatabase.GetAssetOrScenePath(newScene);
                }
                var isInBuildSettings = IsInBuildSettings(newScene);
                if (isInBuildSettings)
                {
                    EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.InBuildSettings".Traslate(), MessageType.Info);
                }
                else
                {
                    EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.SceneNotInBuildSettings".Traslate(), MessageType.Error);
                }
                using (new EditorGUI.DisabledScope(!newScene || isInBuildSettings))
                {
                    if (GUILayout.Button("UnityPlugin.SceneWindow.AddSceneToBuildSettings".Traslate()))
                    {
                        var buildSettingsScene = new EditorBuildSettingsScene(unitySceneDataControl.Scene, true);
                        EditorBuildSettings.scenes = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes)
                        {
                            buildSettingsScene
                        }.ToArray();
                    }
                }
            }
            else
            {
                GUILayout.Label("Select an scene in the left");
                var scene1GUID        = AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets("_Scene1")[0]);
                var scene1            = AssetDatabase.LoadAssetAtPath(scene1GUID, typeof(SceneAsset));
                var isInBuildSettings = IsInBuildSettings(scene1);
                if (isInBuildSettings)
                {
                    EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.MainSceneInBuildSettings".Traslate(), MessageType.Info);
                }
                else
                {
                    EditorGUILayout.HelpBox("UnityPlugin.SceneWindow.MainSceneNotInBuildSettings".Traslate(), MessageType.Error);
                }
                using (new EditorGUI.DisabledScope(!scene1 || isInBuildSettings))
                {
                    if (GUILayout.Button("UnityPlugin.SceneWindow.AddSceneToBuildSettings".Traslate()))
                    {
                        var buildSettingsScene = new EditorBuildSettingsScene(scene1GUID, true);
                        EditorBuildSettings.scenes = new List <EditorBuildSettingsScene>(EditorBuildSettings.scenes)
                        {
                            buildSettingsScene
                        }.ToArray();
                    }
                }
            }
        }
Exemplo n.º 20
0
    public static void SplitSelectScene()
    {
        SceneAsset sceneAsset = Selection.activeObject as SceneAsset;
        var        scene      = EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(sceneAsset), OpenSceneMode.Additive);

        var terrainRootGo = GameObject.Find("/Terrain");

        try
        {
            if (terrainRootGo == null)
            {
                return;
            }

            var terrainRoot = terrainRootGo.transform;

            //Vector3 rootPos = terrainRoot.position;
            int width = 0;
            int depth = 0;
            int size  = 0;

            List <TerrainTrunk> trunks;

            GetTrunksSettings(terrainRoot, out width, out depth, out size, out trunks);

            // Group assets
            var bigAssetRoot = GameObject.Find("Asset_Big");
            if (bigAssetRoot != null)
            {
                GroupBigAssets(bigAssetRoot.transform, trunks, size);
            }

            var smallAssetRoot = GameObject.Find("Asset_Small");
            if (smallAssetRoot != null)
            {
                GroupSmallAssets(smallAssetRoot.transform, trunks, size);
            }

            // Create terrain trunks
            var sceneTrunkData = terrainRootGo.SafeAddComponent <SceneTrunkMgr>();
            sceneTrunkData.width     = width;
            sceneTrunkData.depth     = depth;
            sceneTrunkData.trunkSize = size;
            sceneTrunkData.entries   = new SceneTrunkDataEntry[trunks.Count];

            SaveTrunksAsScenes(scene.name, sceneTrunkData, trunks);

            // Destroy terrains
            while (terrainRoot.childCount > 0)
            {
                var child = terrainRoot.GetChild(terrainRoot.childCount - 1);
                Object.DestroyImmediate(child.gameObject);
            }

            SaveScene(scene);
        }
        finally
        {
            EditorSceneManager.CloseScene(scene, true);
        }
    }
Exemplo n.º 21
0
 public static string CueEventParamGUI(Rect rect, string param, System.Type type)
 {
     if (type.Equals(typeof(void)))
     {
         return("");
     }
     else if (type.Equals(typeof(string)))
     {
         try {
             return(EditorGUI.TextField(rect, param));
         } catch {
             return(EditorGUI.TextField(rect, ""));
         }
     }
     else if (type.Equals(typeof(int)))
     {
         try {
             return(EditorGUI.IntField(rect, int.Parse(param)).ToString());
         } catch {
             return(EditorGUI.IntField(rect, 0).ToString());
         }
     }
     else if (type.Equals(typeof(float)))
     {
         try { return(EditorGUI.FloatField(rect, float.Parse(param)).ToString()); }
         catch {
             return(EditorGUI.FloatField(rect, 0).ToString());
         }
     }
     else if (type.Equals(typeof(bool)))
     {
         try { return(EditorGUI.Toggle(rect, bool.Parse(param)).ToString()); }
         catch
         {
             return(EditorGUI.Toggle(rect, false).ToString());
         }
     }
     else if (type.Equals(typeof(GameObject)))
     {
         try{
             GameObject o    = (GameObject)EditorGUI.ObjectField(rect, GetGameObjectByPathOrGUID(param), typeof(GameObject), true);
             string     path = AssetDatabase.GetAssetOrScenePath(o);
             if (path.EndsWith(".unity"))
             {
                 return(GetHierarchyPath(o.transform));//Scene上のやつだったら
             }
             else
             {
                 return(AssetDatabase.AssetPathToGUID(path));
             }
         }
         catch {
             EditorGUI.ObjectField(rect, null, typeof(GameObject), true);
             return("");
         }
     }
     else if (type.IsSubclassOf(typeof(Object)))
     {
         Object go = (Object)EditorGUI.ObjectField(rect, AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(param), typeof(Object)), typeof(Object), false);
         return(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(go)));
     }
     return("");
 }
        /// <summary>
        /// DO NOT USE: Working on, where every texture is grabbed from the object
        /// </summary>
        public static void ExportTextureFromAMesh(MeshRenderer meshRenderer, string materialFolder, string fullTextureFolder)
        {
            // 1. Need to copy the texture to the new path


            // Go through all materials in the mesh renderer and export them as some materials

            int length = meshRenderer.sharedMaterials.Length;

            for (int materialIndex = 0; materialIndex < length; materialIndex++)
            {
                Material currentMaterial = meshRenderer.sharedMaterials[materialIndex];
                Shader   shader          = currentMaterial.shader;

                int propertyCount = ShaderUtil.GetPropertyCount(shader);

                // Copies all the textures to the file
                for (int i = 0; i < propertyCount; i++)
                {
                    ShaderUtil.ShaderPropertyType propType = ShaderUtil.GetPropertyType(shader, i);
                    if (propType == ShaderUtil.ShaderPropertyType.TexEnv)
                    {
                        Texture texture = currentMaterial.GetTexture(ShaderUtil.GetPropertyName(shader, i));

                        if (texture != null)
                        {
                            string texturePath           = UtiltiesHiFi.GetAssetPathFolder() + AssetDatabase.GetAssetOrScenePath(texture);
                            string newTextureName        = UtiltiesHiFi.GetFileName(texturePath);
                            string newTexturePathAndName = fullTextureFolder + newTextureName;
                            File.Copy(texturePath, newTexturePathAndName);
                        }
                    }
                }
            }
        }
        static SpineArmatureEditor CreateSpineByDir(Bone2DSetupEditor.DisplayType displayType)
        {
            if (Selection.activeObject != null)
            {
                string dirPath = AssetDatabase.GetAssetOrScenePath(Selection.activeObject);
                if (File.Exists(dirPath))
                {
                    dirPath = dirPath.Substring(0, dirPath.LastIndexOf("/"));
                }
                if (Directory.Exists(dirPath))
                {
                    string        animJsonPath = null, textureFilePath = null;
                    List <string> texturePaths = new List <string>();
                    foreach (string path in Directory.GetFiles(dirPath))
                    {
                        if (path.IndexOf(".atlas") > -1 && path.LastIndexOf(".meta") == -1)
                        {
                            textureFilePath = path;
                            continue;
                        }
                        if (path.IndexOf(".png") > -1 && path.LastIndexOf(".meta") == -1)
                        {
                            texturePaths.Add(path);
                            continue;
                        }
                        if (path.IndexOf(".json") > -1 && path.LastIndexOf(".meta") == -1)
                        {
                            animJsonPath = path;
                        }
                    }
                    string texturePath = null;
                    if (texturePaths.Count > 0)
                    {
                        texturePath = texturePaths[0];
                    }
                    if (!string.IsNullOrEmpty(animJsonPath) && !string.IsNullOrEmpty(texturePath) && !string.IsNullOrEmpty(textureFilePath))
                    {
                        SpineArmatureEditor instance = ScriptableObject.CreateInstance <SpineArmatureEditor>();
                        instance.displayType    = displayType;
                        instance.altasTextAsset = LoadAtlas(Application.dataPath + "/" + textureFilePath.Substring(6));
                        instance.altasTexture   = AssetDatabase.LoadAssetAtPath <Texture2D>(texturePath);
                        instance.animTextAsset  = AssetDatabase.LoadAssetAtPath <TextAsset>(animJsonPath);

                        if (texturePaths.Count > 1)
                        {
                            instance.otherTextures = new Atlas[texturePaths.Count - 1];
                        }
                        for (int i = 1; i < texturePaths.Count; ++i)
                        {
                            Atlas atlas = new Atlas();
                            atlas.atlasText = instance.altasTextAsset;
                            atlas.texture   = AssetDatabase.LoadAssetAtPath <Texture2D>(texturePaths[i]);
                            instance.otherTextures[i - 1] = atlas;
                        }
                        if (instance.altasTexture && !string.IsNullOrEmpty(instance.altasTextAsset) && instance.animTextAsset)
                        {
                            return(instance);
                        }
                    }
                    else if (displayType == Bone2DSetupEditor.DisplayType.SpriteRender && !string.IsNullOrEmpty(animJsonPath))
                    {
                        string spritesPath = null;
                        foreach (string path in Directory.GetDirectories(dirPath))
                        {
                            if (path.LastIndexOf("texture") > -1)
                            {
                                spritesPath = path;
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(spritesPath))
                        {
                            Dictionary <string, Sprite> spriteKV = new Dictionary <string, Sprite>();
                            foreach (string path in Directory.GetFiles(spritesPath))
                            {
                                if (path.LastIndexOf(".png") > -1 && path.LastIndexOf(".meta") == -1)
                                {
                                    Sprite sprite = AssetDatabase.LoadAssetAtPath <Sprite>(path);
                                    spriteKV[sprite.name] = sprite;
                                }
                            }
                            if (spriteKV.Count > 0)
                            {
                                SpineArmatureEditor instance = ScriptableObject.CreateInstance <SpineArmatureEditor>();
                                instance.displayType   = displayType;
                                instance.spriteKV      = spriteKV;
                                instance.animTextAsset = AssetDatabase.LoadAssetAtPath <TextAsset>(animJsonPath);
                                return(instance);
                            }
                        }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 24
0
 private void OpenSpectateExampleScene()
 {
     UnityEditor.SceneManagement.EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(_exampleSpectate));
 }
Exemplo n.º 25
0
        private void DisplayLoaderSelectionUI()
        {
            if (!m_HasCompletedRequest)
            {
                return;
            }

            if (!m_XRPackages.Any())
            {
                EditorGUILayout.HelpBox(Content.k_ProvidersUnavailable, MessageType.Error);
                return;
            }

            if (!m_HasInstalledProviders)
            {
                EditorGUILayout.HelpBox(Content.k_NeedToInstallAProvider, MessageType.Warning);
                return;
            }

            BuildTargetGroup buildTargetGroup   = EditorGUILayout.BeginBuildTargetSelectionGrouping();
            bool             buildTargetChanged = m_LastBuildTargetGroup != buildTargetGroup;

            if (buildTargetChanged)
            {
                m_LastBuildTargetGroup = buildTargetGroup;
            }

            XRGeneralSettings settings = currentSettings.SettingsForBuildTarget(buildTargetGroup);

            if (settings == null)
            {
                settings = ScriptableObject.CreateInstance <XRGeneralSettings>() as XRGeneralSettings;
                currentSettings.SetSettingsForBuildTarget(buildTargetGroup, settings);
                settings.name = $"{buildTargetGroup.ToString()} Settings";
                AssetDatabase.AddObjectToAsset(settings, AssetDatabase.GetAssetOrScenePath(currentSettings));
            }

            var serializedSettingsObject = new SerializedObject(settings);

            serializedSettingsObject.Update();

            SerializedProperty initOnStart = serializedSettingsObject.FindProperty("m_InitManagerOnStart");

            EditorGUILayout.PropertyField(initOnStart, Content.s_LoaderInitOnStartLabel);

            SerializedProperty loaderProp = serializedSettingsObject.FindProperty("m_LoaderManagerInstance");

            if (!CachedSettingsEditor.ContainsKey(buildTargetGroup))
            {
                CachedSettingsEditor.Add(buildTargetGroup, null);
            }

            if (loaderProp.objectReferenceValue == null)
            {
                var xrManagerSettings = ScriptableObject.CreateInstance <XRManagerSettings>() as XRManagerSettings;
                xrManagerSettings.name = $"{buildTargetGroup.ToString()} Providers";
                AssetDatabase.AddObjectToAsset(xrManagerSettings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                loaderProp.objectReferenceValue = xrManagerSettings;
                serializedSettingsObject.ApplyModifiedProperties();
            }

            var obj = loaderProp.objectReferenceValue;

            if (obj != null)
            {
                loaderProp.objectReferenceValue = obj;

                if (CachedSettingsEditor[buildTargetGroup] == null)
                {
                    CachedSettingsEditor[buildTargetGroup] = Editor.CreateEditor(obj) as XRManagerSettingsEditor;

                    if (CachedSettingsEditor[buildTargetGroup] == null)
                    {
                        Debug.LogError("Failed to create a view for XR Manager Settings Instance");
                    }
                }

                if (CachedSettingsEditor[buildTargetGroup] != null)
                {
                    if (buildTargetChanged)
                    {
                        CachedSettingsEditor[buildTargetGroup].BuildTarget = buildTargetGroup;
                        CachedSettingsEditor[buildTargetGroup].Reload();
                    }
                    CachedSettingsEditor[buildTargetGroup].OnInspectorGUI();
                }
            }
            else if (obj == null)
            {
                settings.AssignedSettings       = null;
                loaderProp.objectReferenceValue = null;
            }

            EditorGUILayout.EndBuildTargetSelectionGrouping();

            serializedSettingsObject.ApplyModifiedProperties();
        }
Exemplo n.º 26
0
 private void OpenArtisticExampleScene()
 {
     UnityEditor.SceneManagement.EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(_exampleArtistic));
 }
Exemplo n.º 27
0
        void SetTextureFormat(Texture2D tx, TextureFormatInfo tfi, bool addToList, bool setNormalMap)
        {
            AssetImporter ai = AssetImporter.GetAtPath(AssetDatabase.GetAssetOrScenePath(tx));

            if (ai != null && ai is UnityEditor.TextureImporter)
            {
                string s;
                if (addToList)
                {
                    s = "Setting texture format for ";
                }
                else
                {
                    s = "Restoring texture format for ";
                }
                s += tx + " to " + tfi.format;
                if (tfi.platform != null)
                {
                    s += " setting platform override format for " + tfi.platform + " to " + tfi.platformOverrideFormat;
                }
                Debug.Log(s);
                TextureImporter   textureImporter = (TextureImporter)ai;
                TextureFormatInfo restoreTfi      = new TextureFormatInfo(textureImporter.textureFormat,
                                                                          tfi.platform,
                                                                          TextureImporterFormat.AutomaticTruecolor,
                                                                          textureImporter.normalmap);
                string platform = tfi.platform;
                bool   doImport = false;
                if (platform != null)
                {
                    int maxSize;
                    TextureImporterFormat f;
                    textureImporter.GetPlatformTextureSettings(platform, out maxSize, out f);
                    restoreTfi.platformOverrideFormat = f;
                    if (f != 0)                      //f == 0 means no override or platform doesn't exist
                    {
                        textureImporter.SetPlatformTextureSettings(platform, maxSize, tfi.platformOverrideFormat);
                        doImport = true;
                    }
                }

                if (textureImporter.textureFormat != tfi.format)
                {
                    textureImporter.textureFormat = tfi.format;
                    doImport = true;
                }
                if (textureImporter.normalmap && !setNormalMap)
                {
                    textureImporter.normalmap = false;
                    doImport = true;
                }
                if (!textureImporter.normalmap && setNormalMap)
                {
                    textureImporter.normalmap = true;
                    doImport = true;
                }
                if (addToList && !_textureFormatMap.ContainsKey(tx))
                {
                    _textureFormatMap.Add(tx, restoreTfi);
                }
                if (doImport)
                {
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetOrScenePath(tx), ImportAssetOptions.ForceUpdate);
                }
            }
        }
Exemplo n.º 28
0
 private void OpenWitchLabExampleScene()
 {
     UnityEditor.SceneManagement.EditorSceneManager.OpenScene(AssetDatabase.GetAssetOrScenePath(_exampleWitchLab));
 }
Exemplo n.º 29
0
		public static void PrintDependencies(GameObject targetGO)
		{
#if UNITY_EDITOR
			Debug.Log("Print Dependcies: target: " + targetGO.name);
			UnityEngine.Object[] depends = HEU_EditorUtility.CollectDependencies(targetGO);
			foreach (UnityEngine.Object obj in depends)
			{
				Debug.LogFormat("Dependent: name={0}, type={1}, path={2}, persist={3}, native={4}", obj.name, obj.GetType().ToString(), AssetDatabase.GetAssetOrScenePath(obj), EditorUtility.IsPersistent(obj),
					AssetDatabase.IsNativeAsset(obj));
			}
#endif
		}
Exemplo n.º 30
0
        public override Texture2D GetPreview(Object obj, int width, int height)
        {
            var path = AssetDatabase.GetAssetOrScenePath(obj);

            return(Utils.GetAssetPreviewFromPath(path, new Vector2(width, height), FetchPreviewOptions.Preview2D));
        }