// Assign default material to Virtual Button.
    public static void CreateMaterial(IEditorVirtualButtonBehaviour vb)
    {
        // Load reference material
        string referenceMaterialPath =
            QCARUtilities.GlobalVars.VIRTUAL_BUTTON_MATERIAL_PATH;
        Material referenceMaterial =
            (Material)AssetDatabase.LoadAssetAtPath(referenceMaterialPath,
                                                    typeof(Material));

        if (referenceMaterial == null)
        {
            Debug.LogError("Could not find reference material at " +
                           referenceMaterialPath +
                           " please reimport Unity package.");
            return;
        }

        // If the texture is null we simply assign a default material
        vb.renderer.sharedMaterial = referenceMaterial;

        // Cleanup assets that have been created temporarily.
        EditorUtility.UnloadUnusedAssets();
    }
Exemplo n.º 2
0
	    public static void Show<T>(
			[NotNull] Action<Object> callback, 
			[CanBeNull] string[] labels = null, 
			bool enableSelectionOnClick = false, 
			[CanBeNull] Object selectedAsset = null)
	    {
	        var w = CreateInstance<AssetPicker>();
	        w.enableSelectionOnClick = enableSelectionOnClick;
			w.AssetType = typeof(T);
	        w.selectionCallback = callback;
	        w.labelsFilter = labels;
	        w.UpdateAssetList();
            if (selectedAsset)
            {
                var assetPath = AssetDatabase.GetAssetPath(selectedAsset);
                w.SelectedAssetEntry =
                    w.loadedAssetsFlat.FirstOrDefault(e => e.Path == assetPath);
                w.scrollToSelected = true;
            }
            w.ShowAuxWindow();
            w.focusNameFilter = true;
            w.Focus();
        }
Exemplo n.º 3
0
	public static void CreateAssetBunldesALL ()
	{

		Caching.CleanCache ();

		string Path = Application.dataPath + "/StreamingAssets/ALL.assetbundle";

		Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);

		foreach (Object obj in SelectedAsset) 
		{
			Debug.Log ("Create AssetBunldes name :" + obj);
		}

		//这里注意第二个参数就行
		if (BuildPipeline.BuildAssetBundle (null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies,BuildTarget.iOS)) 
		{
			AssetDatabase.Refresh ();
		} 
		else {

		}
	}
Exemplo n.º 4
0
    private static void DisableAllUtilitiesPluginPackages()
    {
        List <PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();

        foreach (PluginPackage pluginPkg in allUtilsPluginPkgs)
        {
            foreach (string path in pluginPkg.Plugins.Values)
            {
                if ((Directory.Exists(path)) || (File.Exists(path)))
                {
                    string basePath        = GetCurrentProjectPath();
                    string relPath         = path.Substring(basePath.Length + 1);
                    string relDisabledPath = relPath + GetDisabledPluginSuffix();

                    AssetDatabase.MoveAsset(relPath, relDisabledPath);
                    AssetDatabase.ImportAsset(relDisabledPath, ImportAssetOptions.ForceUpdate);
                }
            }
        }

        AssetDatabase.Refresh();
        AssetDatabase.SaveAssets();
    }
Exemplo n.º 5
0
        public static void Cleanup()
        {
            if (cleanupDone)
            {
                return;
            }
            cleanupDone = true;

            TryMigrateSettings();
            TryMigrateLegacyInjectionWhitelist();

            if (File.Exists(InjectionConstants.DataFilePath))
            {
#if ACTK_DEBUG
                Debug.Log(ACTkConstants.LogPrefix + "Data file found and going to be removed: " + InjectionConstants.DataFilePath);
#endif
                EditorTools.DeleteFile(InjectionConstants.DataFilePath);
                EditorTools.DeleteFile(InjectionConstants.DataFileMetaPath);
                EditorTools.RemoveDirectoryIfEmpty(InjectionConstants.ResourcesFolder);

                AssetDatabase.Refresh();
            }
        }
Exemplo n.º 6
0
    /// <summary>
    /// 对依赖的字体进行打包,返回打包结果路径
    /// </summary>
    /// <param name="font"></param>
    /// <returns></returns>
    public static string BuildFont(Font font)
    {
        string fontAssetPath = AssetDatabase.GetAssetPath(font);

        if (string.IsNullOrEmpty(fontAssetPath) || fontAssetPath == "Library/unity default resources")
        {
            Log.Error("[BuildFont]无法打包字体...{0}", font);
            return(null);
        }
        //fontAssetPath = __GetPrefabBuildPath(fontAssetPath).Replace("Atlas_", "");
        //string[] splitArr = fontAssetPath.Split('/');

        bool needBuild = AssetVersionControl.TryCheckNeedBuildWithMeta(fontAssetPath);

        if (needBuild)
        {
            AssetVersionControl.TryMarkBuildVersion(fontAssetPath);
        }

        var result = DoBuildAssetBundle("Font/Font_" + font.name, font, needBuild);

        return(result.Path);
    }
Exemplo n.º 7
0
        private void RefreshTextureAssets()
        {
            _texture2Ds.Clear();
            string[] guids = AssetDatabase.FindAssets("t:Texture2D");
            for (int i = 0; i < guids.Length; i++)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);

                Texture2D textureAsset = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath);
                if (textureAsset != null)
                {
                    if (textureAsset.width <= 64 || textureAsset.height <= 64)
                    {
                        //너무 작은건 패스한다.
                        continue;
                    }

                    if (_isSearched)
                    {
                        if (!textureAsset.name.Contains(_strSearchKeyword))
                        {
                            //검색이 되지 않는다면 패스
                            continue;
                        }
                    }

                    _texture2Ds.Add(textureAsset);
                }
            }
            if (_curSelectedTexture2D != null)
            {
                if (!_texture2Ds.Contains(_curSelectedTexture2D))
                {
                    _curSelectedTexture2D = null;
                }
            }
        }
    private static void BuildApkInner(string idName, string apkName, string destPath, bool run, string[] levels)
    {
        GeneralSettings();

        PlayerSettings.productName = "Controller6DofTest";
#if UNITY_5_6_OR_NEWER
        PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "com.htc.vr.samples." + idName);
#else
        PlayerSettings.bundleIdentifier = "com.htc.vr.samples.Controller6DofTest.unity";
#endif
        Texture2D icon1 = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Samples/Controller6DofTest/wave_Controller6DofTest_unity_app_icon/res/mipmap-mdpi/wave_Controller6DofTest_unity_app_icon.png", typeof(Texture2D));
        Texture2D icon2 = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Samples/Controller6DofTest/wave_Controller6DofTest_unity_app_icon/res/mipmap-hdpi/wave_Controller6DofTest_unity_app_icon.png", typeof(Texture2D));
        Texture2D icon3 = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Samples/Controller6DofTest/wave_Controller6DofTest_unity_app_icon/res/mipmap-xhdpi/wave_Controller6DofTest_unity_app_icon.png", typeof(Texture2D));
        Texture2D icon4 = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Samples/Controller6DofTest/wave_Controller6DofTest_unity_app_icon/res/mipmap-xxhdpi/wave_Controller6DofTest_unity_app_icon.png", typeof(Texture2D));
        Texture2D icon5 = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Samples/Controller6DofTest/wave_Controller6DofTest_unity_app_icon/res/mipmap-xxxhdpi/wave_Controller6DofTest_unity_app_icon.png", typeof(Texture2D));

        if (icon5 == null)
        {
            Debug.LogError("Fail to read app icon");
        }

        Texture2D[] group = { icon5, icon4, icon3, icon2, icon1, icon1 };

        PlayerSettings.SetIconsForTargetGroup(BuildTargetGroup.Android, group);
        PlayerSettings.gpuSkinning = false;
#if UNITY_2017_2_OR_NEWER
        PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true);
#else
        PlayerSettings.mobileMTRendering = true;
#endif
        PlayerSettings.graphicsJobs             = true;
        PlayerSettings.Android.minSdkVersion    = AndroidSdkVersions.AndroidApiLevel25;
        PlayerSettings.Android.targetSdkVersion = AndroidSdkVersions.AndroidApiLevel25;

        string outputFilePath = string.IsNullOrEmpty(destPath) ? apkName : destPath + "/" + apkName;
        BuildPipeline.BuildPlayer(levels, outputFilePath, BuildTarget.Android, run ? BuildOptions.AutoRunPlayer : BuildOptions.None);
    }
Exemplo n.º 9
0
        static GameObject CreateScrollbar()
        {
            // Create GOs Hierarchy
            GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", thinElementSize);
            GameObject sliderArea    = CreateUIObject("Sliding Area", scrollbarRoot);
            GameObject handle        = CreateUIObject("Handle", sliderArea);

            Image bgImage = scrollbarRoot.AddComponent <Image>();

            bgImage.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>(bgPath);
            bgImage.type   = Image.Type.Sliced;
            bgImage.color  = defaultSelectableColor;

            Image handleImage = handle.AddComponent <Image>();

            handleImage.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>(spritePath);
            handleImage.type   = Image.Type.Sliced;
            handleImage.color  = defaultSelectableColor;

            RectTransform sliderAreaRect = sliderArea.GetComponent <RectTransform>();

            sliderAreaRect.sizeDelta = new Vector2(-20, -20);
            sliderAreaRect.anchorMin = Vector2.zero;
            sliderAreaRect.anchorMax = Vector2.one;

            RectTransform handleRect = handle.GetComponent <RectTransform>();

            handleRect.sizeDelta = new Vector2(20, 20);

            Scrollbar scrollbar = scrollbarRoot.AddComponent <Scrollbar>();

            scrollbar.handleRect    = handleRect;
            scrollbar.targetGraphic = handleImage;
            SetDefaultColorTransitionValues(scrollbar);

            return(scrollbarRoot);
        }
Exemplo n.º 10
0
    void OnGUI()
    {
        tex = new Texture2D(1, 1, TextureFormat.RGBA32, false);
        initColor();
        tex.SetPixel(0, 0, background);
        tex.Apply();
        GUI.DrawTexture(new Rect(0, 0, position.width, position.height), tex, ScaleMode.StretchToFill);
        GUI.Label(new Rect(200, 200, 100, 100), "");
        GUI.TextField(new Rect(20, 20, 70, 30), "");
        GUI.backgroundColor = buttons;
        Texture logo = (Texture)AssetDatabase.LoadAssetAtPath("Assets/KorikasAvatarPlugin/Korikas Avatar Plugin/logo.png", typeof(Texture));

        GUI.DrawTexture(new Rect(0, 0, position.width, 70), logo, ScaleMode.ScaleAndCrop);

        string[] toolbarString = { "gestures", "copy", "credits" };
        toolbarInt = GUILayout.Toolbar(toolbarInt, toolbarString);

        GUILayout.Space(50);
        scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true, GUILayout.Width(position.width), GUILayout.Height(position.height - 74));
        switch (toolbarInt)
        {
        case 0:
            toolbarInt = 0;
            RenderGestureTab();
            break;

        case 1:
            toolbarInt = 1;
            RenderCopyContentsTab();
            break;

        case 2:
            RenderCreditsTab();
            break;
        }
        EditorGUILayout.EndScrollView();
    }
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        _ImportFilePathList.Clear();

        if ((importedAssets != null) && (importedAssets.Length > 0))
        {
            for (int i = 0; i < importedAssets.Length; i++)
            {
                string str = importedAssets[i];
                OnImportedAssets(str);
            }
        }

        if ((deletedAssets != null) && (deletedAssets.Length > 0))
        {
            for (int i = 0; i < deletedAssets.Length; i++)
            {
                string str = deletedAssets[i];
                OnDeleteAssets(str);
            }
        }

        OnImportXmls(importedAssets, deletedAssets);

        /*for( int i=0; i<movedAssets.Length; i++ ) {
         *      Debug.Log("Moved Asset: " + movedAssets[i] + " from: " + movedFromAssetPaths[i]);
         * }*/

        /*for( int i=0; i<_ImportFilePathList.Count; i++ ) {
         *  AssetDatabase.ImportAsset( _ImportFilePathList[i] );
         * }*/

        if (_ImportFilePathList.Count > 0)
        {
            AssetDatabase.Refresh();
        }
    }
        private bool SetCamera()
        {
            CinemachineBrain brain = FindObjectOfType <CinemachineBrain>();

            if (brain == null)
            {
                Undo.AddComponent <CinemachineBrain>(Camera.main.transform.gameObject);
            }

            CinemachineStateDrivenCamera camera = FindObjectOfType <CinemachineStateDrivenCamera>();

            if (camera == null)
            {
                camera = AssetDatabase.LoadAssetAtPath <CinemachineStateDrivenCamera>("Assets/Dias Games/Climbing System/Prefabs/Climbing Camera State Driven.prefab");
                Object newCam = PrefabUtility.InstantiatePrefab(camera);

                GameObject character = GameObject.FindGameObjectWithTag("Player");
                if (character != null)
                {
                    Transform target = character.transform.Find("Camera Track Pos");

                    SerializedObject cameraObj = new SerializedObject(newCam);
                    cameraObj.Update();

                    cameraObj.FindProperty("m_LookAt").objectReferenceValue         = target;
                    cameraObj.FindProperty("m_Follow").objectReferenceValue         = target;
                    cameraObj.FindProperty("m_AnimatedTarget").objectReferenceValue = character.GetComponent <Animator>();

                    cameraObj.ApplyModifiedProperties();
                }


                return(true);
            }

            return(false);
        }
Exemplo n.º 13
0
    static void ClearLuaWraps()
    {
        string[] files = Directory.GetFiles(CustomSettings.saveDir, "*.cs", SearchOption.TopDirectoryOnly);

        for (int i = 0; i < files.Length; i++)
        {
            File.Delete(files[i]);
        }

        ToLuaExport.Clear();
        List<DelegateType> list = new List<DelegateType>();
        ToLuaExport.GenDelegates(list.ToArray());
        ToLuaExport.Clear();

        StringBuilder sb = new StringBuilder();
        sb.AppendLineEx("using System;");
        sb.AppendLineEx("using LuaInterface;");
        sb.AppendLineEx();
        sb.AppendLineEx("public static class LuaBinder");
        sb.AppendLineEx("{");
        sb.AppendLineEx("\tpublic static void Bind(LuaState L)");
        sb.AppendLineEx("\t{");
        sb.AppendLineEx("\t\tthrow new LuaException(\"Please generate LuaBinder files first!\");");
        sb.AppendLineEx("\t}");
        sb.AppendLineEx("}");

        string file = CustomSettings.saveDir + "LuaBinder.cs";

        using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8))
        {
            textWriter.Write(sb.ToString());
            textWriter.Flush();
            textWriter.Close();
        }

        AssetDatabase.Refresh();
    }
    static bool CheckTargetCompressTexture(string path)
    {
        if (String.IsNullOrEmpty(path))
        {
            return(false);
        }
        Texture2D tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;

        switch (EditorUserBuildSettings.activeBuildTarget)
        {
        case BuildTarget.Android:
            if (tex.format == TextureFormat.ETC_RGB4)
            {
                return(false);
            }
            break;

#if UNITY_5
        case BuildTarget.iOS:
#else
        case BuildTarget.iPhone:
#endif
            if (tex.format == TextureFormat.PVRTC_RGB4 || tex.format == TextureFormat.PVRTC_RGBA4)
            {
                return(false);
            }
            break;

        default:
            if (tex.format == TextureFormat.DXT1 || tex.format == TextureFormat.DXT5)
            {
                return(false);
            }
            break;
        }
        return(true);
    }
Exemplo n.º 15
0
    static void BuildLuaBundle(string subDir, string sourceDir)
    {
        string[] files      = Directory.GetFiles(sourceDir + subDir, "*.bytes");
        string   bundleName = subDir == null ? "lua.unity3d" : "lua" + subDir.Replace('/', '_') + ".unity3d";

        bundleName = bundleName.ToLower();

#if UNITY_4_6 || UNITY_4_7
        List <Object> list = new List <Object>();

        for (int i = 0; i < files.Length; i++)
        {
            Object obj = AssetDatabase.LoadMainAssetAtPath(files[i]);
            list.Add(obj);
        }

        BuildAssetBundleOptions options = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle;

        if (files.Length > 0)
        {
            string output = string.Format("{0}/{1}/" + bundleName, Application.streamingAssetsPath, GetOS());
            File.Delete(output);
            BuildPipeline.BuildAssetBundle(null, list.ToArray(), output, options, EditorUserBuildSettings.activeBuildTarget);
        }
#else
        for (int i = 0; i < files.Length; i++)
        {
            AssetImporter importer = AssetImporter.GetAtPath(files[i]);

            if (importer)
            {
                importer.assetBundleName    = bundleName;
                importer.assetBundleVariant = null;
            }
        }
#endif
    }
Exemplo n.º 16
0
        protected VisualEffectResource GetCurrentResource()
        {
            var objs = Selection.objects;

            VisualEffectResource selectedResource = null;

            if (objs != null && objs.Length == 1)
            {
                if (objs[0] is VisualEffectAsset)
                {
                    VisualEffectAsset asset = objs[0] as VisualEffectAsset;
                    selectedResource = asset.GetResource();
                }
                else if (objs[0] is VisualEffectResource)
                {
                    selectedResource = objs[0] as VisualEffectResource;
                }
            }
            if (selectedResource == null)
            {
                int instanceID = Selection.activeInstanceID;

                if (instanceID != 0)
                {
                    string path = AssetDatabase.GetAssetPath(instanceID);
                    if (path.EndsWith(VisualEffectResource.Extension))
                    {
                        selectedResource = VisualEffectResource.GetResourceAtPath(path);
                    }
                }
            }
            if (selectedResource == null && m_DisplayedResource != null)
            {
                selectedResource = m_DisplayedResource;
            }
            return(selectedResource);
        }
Exemplo n.º 17
0
        public static void GameLevelLayout()
        {
            string assetPath = @"Assets/Resources/map.asset";

            if (Selection.activeGameObject == null)
            {
                throw new UnityException("must select Map");
            }

            Transform map = Selection.activeGameObject.transform;

            MapConfig info    = AssetDatabase.LoadAssetAtPath(assetPath, typeof(MapConfig)) as MapConfig;
            bool      isExist = (info != null);

            if (info == null)
            {
                Debug.Log("AssetDatabase not exist MapConfig");
                info = ScriptableObject.CreateInstance <MapConfig>() as MapConfig;
            }

            info.MapInfo = new Vector3 [map.childCount];
            for (int i = 0, L = map.childCount; i < L; ++i)
            {
                Transform t = map.GetChild(i);
                info.MapInfo [i] = t.localPosition;
            }

            if (!isExist)
            {
                AssetDatabase.CreateAsset(info, assetPath);
                return;
            }

            // 这里很重要,如果没有告诉unity已经被改变。它只写入内存,没有写入磁盘
            EditorUtility.SetDirty(info);
            AssetDatabase.SaveAssets();
        }
        public static string CopyOrCreateMesh(GameObject geometryObject, bool isCollisionGeometry)
        {
            string prefabPath = GetPrefabPath(geometryObject);

            bool foundExistingColladaOrStl = false;

            if (prefabPath != null && prefabPath != "")
            {
                if (Path.GetExtension(prefabPath).ToLower() == ".dae")
                {
                    foundExistingColladaOrStl = true;
                }
                else //Find STL file that corresponds to the prefab, if it already exists
                {
                    string[] foldersToSearch = { Path.GetDirectoryName(prefabPath) };
                    string   prefabName      = Path.GetFileNameWithoutExtension(prefabPath);

                    foreach (string guid2 in AssetDatabase.FindAssets(prefabName, foldersToSearch))
                    {
                        string possiblePath = AssetDatabase.GUIDToAssetPath(guid2);
                        if (possiblePath.ToLower().Contains(".stl"))
                        {
                            prefabPath = possiblePath;
                            foundExistingColladaOrStl = true;
                            break;
                        }
                    }
                }
            }

            if (foundExistingColladaOrStl)
            {
                return(CopyMeshToExportDestination(prefabPath));
            }

            return(CreateNewStlFile(geometryObject, isCollisionGeometry));
        }
Exemplo n.º 19
0
    private void RewriteAllInfoToFile()
    {
        string rotsAllInfo = "";

        for (int j = 0; j < maxTileCount; j++)
        {
            rotsAllInfo += rotsComboInfo[selectedRotIndexes[j]].text + ":";
        }

        string allInfo = "";

        for (int i = 0; i < tcNames.Count; i++)
        {
            string tcName     = tcNames[i].ToString();
            string tcObjsInfo = tcObjs[i].ToString();
            string tcRotsInfo = tcRots[i].ToString();

            if (i == selGridInt)
            {
                tcRotsInfo = rotsAllInfo;
            }

            allInfo += tcName + "$" + tcObjsInfo + "$" + tcRotsInfo + "$|";
        }

        StreamWriter sw = new StreamWriter(path);

        sw.Write("");
        sw.Write(allInfo);
        sw.Close();

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

        LoadInfo();
        LoadTileConnectionInfoByID(selGridInt);
    }
Exemplo n.º 20
0
		public override void ReadFromString( ref string[] nodeParams )
		{
			base.ReadFromString( ref nodeParams ):
			string defaultTextureGUID = GetCurrentParam( ref nodeParams ):
			//m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( textureName ):
			if( UIUtils.CurrentShaderVersion() > 14101 )
			{
				m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( AssetDatabase.GUIDToAssetPath( defaultTextureGUID ) ):
				string materialTextureGUID = GetCurrentParam( ref nodeParams ):
				m_materialValue = AssetDatabase.LoadAssetAtPath<Texture>( AssetDatabase.GUIDToAssetPath( materialTextureGUID ) ):
			}
			else
			{
				m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( defaultTextureGUID ):
			}
			m_isNormalMap = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ):
			m_defaultTextureValue = ( TexturePropertyValues ) Enum.Parse( typeof( TexturePropertyValues ), GetCurrentParam( ref nodeParams ) ):
			m_autocastMode = ( AutoCastType ) Enum.Parse( typeof( AutoCastType ), GetCurrentParam( ref nodeParams ) ):
			m_virtualPreset = ( VirtualPreset ) Enum.Parse( typeof( VirtualPreset ), GetCurrentParam( ref nodeParams ) ):
			m_selectedChannelInt = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ):
			ChangeChannels():
			m_virtualChannel = GetChannel( m_selectedChannelInt ):

			//m_forceNodeUpdate = true:

			//ConfigFromObject( m_defaultValue ):
			if( m_materialValue == null )
			{
				ConfigFromObject( m_defaultValue ):
			}
			else
			{
				CheckTextureImporter( true, true ):
			}
			ConfigureInputPorts():
			ConfigureOutputPorts():
		}
Exemplo n.º 21
0
    /// <summary>
    /// Creates a new CameraViewTarget from the editor's current scene view and
    /// sets it as the currently selected CameraViewTarget's next view.
    /// </summary>
    public void CreateNextViewTarget()
    {
        CameraViewTarget nextViewtarget = ScriptableObject.CreateInstance <CameraViewTarget>();

        nextViewtarget.viewPosition = SceneView.lastActiveSceneView.pivot;
        nextViewtarget.viewRotation = SceneView.lastActiveSceneView.rotation.eulerAngles;
        _viewTarget.nextView        = nextViewtarget;

        string newName = AssetDatabase.GetAssetPath(_viewTarget);
        int    i       = newName.LastIndexOf('_');
        int    k       = newName.LastIndexOf('.');

        newName = newName.Substring(0, k);
        if (i > 0)
        {
            int j;
            if (Int32.TryParse(newName.Substring(i + 1), out j))
            {
                j++;
                newName = newName.Substring(0, i + 1) + j.ToString();
            }
            else
            {
                newName += "0";
            }
        }
        else
        {
            newName += "0";
        }

        string createPath = newName + ".asset";

        AssetDatabase.CreateAsset(nextViewtarget, createPath);

        Debug.Log("View Target created at " + AssetDatabase.GetAssetPath(nextViewtarget));
    }
Exemplo n.º 22
0
        static bool OnOpenedAsset(int instanceID, int line)
        {
            // bail out if we are not using VSCode
            if (!Enabled)
            {
                return(false);
            }

            // current path without the asset folder
            string appPath = ProjectPath;

            // determine asset that has been double clicked in the project view
            UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID);

            if (selected.GetType().ToString() == "UnityEditor.MonoScript" ||
                selected.GetType().ToString() == "UnityEngine.Shader")
            {
                string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected);

                string args = null;
                if (line == -1)
                {
                    args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r";
                }
                else
                {
                    args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r";
                }
                // call 'open'
                CallVSCode(args);

                return(true);
            }

            // Didnt find a code file? let Unity figure it out
            return(false);
        }
Exemplo n.º 23
0
    private void GenerateThumbnail()
    {
        var assetPath           = Path.Combine(Directory.GetCurrentDirectory(), PathUtils.GetProjectPath());
        var thumbnailTargetPath = Path.Combine(assetPath, "thumbs");

        if (!Directory.Exists(thumbnailTargetPath))
        {
            Directory.CreateDirectory(thumbnailTargetPath);
        }

        SetupThumbnailGenerator();
        var index = 0;
        var total = thumbnailTargets.Length;

        try
        {
            EditorUtility.DisplayProgressBar("Generating", "Generating the image...", 0);
            foreach (var thumbnailTarget in thumbnailTargets.OfType <GameObject>())
            {
                var outputPath = Path.Combine(thumbnailTargetPath, $"thumb_{thumbnailTarget.name.ToLower().Replace(" ", "_")}.png");
                GenerateTexture(thumbnailTarget, outputPath, false);
                EditorUtility.DisplayProgressBar("Generating", "Generating the image...", ++index / (float)total);
            }
            EditorApplication.Beep();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        finally
        {
            EditorUtility.ClearProgressBar();
        }

        AssetDatabase.Refresh();
    }
            public void WriteToFile(string fullPath, bool allowOverwriting)
            {
                if (File.Exists(fullPath) && !allowOverwriting)
                {
                    throw new System.AccessViolationException("Tried to write PaletteMap but file already exists. " +
                                                              "\nFile Path: " + fullPath);
                }

                Texture2D texture = CreateAsTexture();

                try {
                    byte[] outTextureData = texture.EncodeToPNG();
                    File.WriteAllBytes(fullPath, outTextureData);
                } catch (System.Exception e) {
                    throw new System.IO.IOException("Encountered IO exception during PaletteMap write: " + e.Message);
                }

                // Force refresh so that we can set its Import settings immediately
                AssetDatabase.ImportAsset(fullPath);

                // Assign correct settings to the file
                TextureImporter textureImporter = AssetImporter.GetAtPath(fullPath) as TextureImporter;

                if (textureImporter == null)
                {
                    throw new System.NullReferenceException("Failed to import file at specified path: " + fullPath);
                }
                textureImporter.textureType         = TextureImporterType.Advanced;
                textureImporter.npotScale           = TextureImporterNPOTScale.None;
                textureImporter.alphaIsTransparency = false;
                textureImporter.mipmapEnabled       = false;
                textureImporter.filterMode          = FilterMode.Point;
                textureImporter.textureFormat       = TextureImporterFormat.Alpha8;

                // Force Unity to see the file and use the new import settings
                AssetDatabase.ImportAsset(fullPath);
            }
Exemplo n.º 25
0
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        foreach (var assetPath in importedAssets)
        {
            if (assetPath.EndsWith(".prefab"))
            {
                var prefab = AssetDatabase.LoadAssetAtPath <GameObject>(assetPath);
                if (prefab == null)
                {
                    continue;
                }

                RemoveMissingScript(prefab);
                var assetImporter = AssetImporter.GetAtPath(assetPath);
                if (assetPath.Contains(AssetPath.UI_WINDOW_PATH))
                {
                    assetImporter.assetBundleName = "ui/window";
                }
                else if (assetPath.Contains(AssetPath.UI_PREFAB_PATH))
                {
                    assetImporter.assetBundleName = "ui/prefab";
                }
                else if (assetPath.Contains(AssetPath.EFFECT_ROOT_PATH))
                {
                    var paths     = assetPath.Split('/');
                    var directroy = paths[paths.Length - 2];
                    assetImporter.assetBundleName = StringUtil.Contact("effect/", directroy);
                }
                else if (assetPath.Contains(AssetPath.MOB_ROOT_PATH))
                {
                    var paths     = assetPath.Split('/');
                    var directroy = paths[paths.Length - 2];
                    assetImporter.assetBundleName = StringUtil.Contact("mob/", directroy);
                }
            }
        }
    }
Exemplo n.º 26
0
        private void OnClick(Button button)
        {
            if (m_author.IsEmpty)
            {
                EditorUtility.DisplayDialog("提示", "请填写作者名", "确认");
                return;
            }

            if (m_moudleName.IsEmpty)
            {
                EditorUtility.DisplayDialog("提示", "请填写模块名", "确认");
                return;
            }

            m_moudleName.Text = TemplateEngine.FormatName(m_moudleName.Text);

            DateTime dt = DateTime.Now;

            TemplateEngine.TemplateBasePath = "Assets/Editor/Module/Template/";
            Dictionary <string, string> valueDic = new Dictionary <string, string>();

            valueDic["Author"]     = m_author.Text;
            valueDic["CreateDate"] = string.Format("{0}.{1}.{2}", dt.Year, dt.Month, dt.Day);
            valueDic["moduleName"] = m_moudleName.Text;
            foreach (Toggle toggle in m_toggleArr)
            {
                if (!toggle.Select)
                {
                    continue;
                }
                string[] param = (string[])toggle.Data;
                TemplateEngine.CreateCodeFile(param[0].Replace("${moduleName}", m_moudleName.Text), param[1], valueDic);
            }
            TemplateEngine.TemplateBasePath = null;
            EditorUtility.DisplayDialog("提示", "处理完毕", "确认");
            AssetDatabase.Refresh();
        }
Exemplo n.º 27
0
    void OnPreprocessTexture()
    {
        ImportProperties importProperties = (ImportProperties)AssetDatabase.LoadAssetAtPath("Assets/Prefabs/ImportProperties.prefab", typeof(ImportProperties));

        if (importProperties && importProperties.enableCustomImportSetting)
        {
            TextureImporter textureImporter = assetImporter as TextureImporter;

            if (importProperties.maxTextureSizeSelected > 0)
            {
                textureImporter.maxTextureSize = importProperties.maxTextureSizeSelected;
            }

            if (importProperties.overrideTexturesForAndroid)
            {
                TextureImporterPlatformSettings androidSettings = textureImporter.GetPlatformTextureSettings("Android");
                androidSettings.overridden     = true;
                androidSettings.maxTextureSize = importProperties.maxTextureSizeSelectedForAndroid;
                textureImporter.SetPlatformTextureSettings(androidSettings);

                Debug.Log("Override Android");
            }
        }
    }
        private void ApplyChangeToModels(string multipleWarning, ModelDataAction action)
        {
            // Dialogue popup warning
            if (_selectedModels.Count > 1)
            {
                if (!EditorUtility.DisplayDialog("Multiple asset confirmation", $"You have {_selectedModels.Count} assets selected. {multipleWarning}", "Yes", "No"))
                {
                    return;
                }
            }

            foreach (var model in _selectedModels)
            {
                string          path = AssetDatabase.GetAssetPath(model);
                CustomAssetData data = CustomAssetData.Get(model) ?? new CustomAssetData();
                data = action(model, data);
                CustomAssetData.Set(path, data);
                AssetDatabase.ImportAsset(path);
            }

            _modelDataDictionary.Clear();

            OnSelectionChanged();
        }
Exemplo n.º 29
0
        public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
        {
            EditorGUI.BeginProperty(_position, _label, _property);

            //load current scene
            var oldScene = AssetDatabase.LoadAssetAtPath <SceneAsset>(_property.stringValue);

            //check if change in inspector
            EditorGUI.BeginChangeCheck();

            //draw scene field as object field as scene asset
            var newScene = EditorGUI.ObjectField(_position, _label, oldScene, typeof(SceneAsset), false) as SceneAsset;

            //did change??
            if (EditorGUI.EndChangeCheck())
            {
                //sure did, I guess
                //set string to path of scene
                string path = AssetDatabase.GetAssetPath(newScene);
                _property.stringValue = path;
            }

            EditorGUI.EndProperty();
        }
Exemplo n.º 30
0
        public void MigrationKeepObjectAndComponentActiveState()
        {
            foreach (var entry in migrationList)
            {
                Type oldType = entry.oldType;
                Type newType = entry.newType;
                Type migrationHandlerType = entry.handler;

                Scene         scene            = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
                GameObject    gameObject       = SetUpGameObjectWithComponentOfType(oldType);
                MonoBehaviour oldTypeComponent = (MonoBehaviour)gameObject.GetComponent(oldType);

                oldTypeComponent.enabled = false;
                gameObject.SetActive(false);

                EditorSceneManager.SaveScene(scene, scenePath);
                assetsForDeletion.Add(scenePath);

                migrationTool.TryAddObjectForMigration(migrationHandlerType, AssetDatabase.LoadAssetAtPath(scenePath, typeof(SceneAsset)));
                migrationTool.MigrateSelection(migrationHandlerType, false);

                var openScene = EditorSceneManager.OpenScene(scenePath);
                foreach (var sceneGameObject in openScene.GetRootGameObjects())
                {
                    Assert.IsNull(sceneGameObject.GetComponent(oldType), $"Migrated component of type {oldType.Name} could not be removed");
                    Assert.IsNotNull(sceneGameObject.GetComponent(newType), $"Migrated component of type {newType.Name} could not be added");

                    // Active state of game object and component is kept
                    Assert.IsFalse(sceneGameObject.activeSelf, $"Active state of migrated game object was not kept during migration with type {migrationHandlerType.Name}");
                    Assert.IsFalse(((MonoBehaviour)sceneGameObject.GetComponent(newType)).enabled, $"Active state of migrated component was not kept during migration with type { migrationHandlerType.Name}");

                    Object.DestroyImmediate(sceneGameObject);
                }
                Object.DestroyImmediate(gameObject);
            }
        }
Exemplo n.º 31
0
        public static void DebugDesign(AssetDatabase assetDatabase, GameDatabase gameDatabase, DesignInfo designIn)
        {
            try
            {

            }
            catch (Exception ex)
            {
                SotsosLog("exception: {0}",ex.Message);
            }
        }