Exemple #1
0
        private void ConvertToSprite(Shape shape)
        {
            string dname = "Assets/Resources/Shapes2D Sprites";
            string fname = dname + "/" + shape.name + ".png";
            string rname = "Shapes2D Sprites/" + shape.name;

            if (!System.IO.Directory.Exists(dname))
            {
                System.IO.Directory.CreateDirectory(dname);
            }
            if (System.IO.File.Exists(fname) &&
                !EditorUtility.DisplayDialog("Overwrite File?",
                                             "A file with the name " + fname + " already exists.  "
                                             + "Are you sure you want to overwrite it?", "Yes", "Cancel"))
            {
                return;
            }

            float         pixelsPerUnit = 100;
            Shapes2DPrefs prefs         = GetPreferences();

            if (prefs)
            {
                pixelsPerUnit = prefs.pixelsPerUnit;
            }
            else
            {
                Debug.LogWarning("Can't find Shapes2D Preferences in Shapes2D/Preferences.  Please re-import Shapes2D.");
            }

            Vector2 pivot = RenderToTexture2D(fname, shape, pixelsPerUnit: pixelsPerUnit);

            // refresh the asset
            AssetDatabase.ImportAsset(fname);

            // set the sprite's pivot point so any rotations/position stay the same
            TextureImporter textureImporter = AssetImporter.GetAtPath(fname)
                                              as TextureImporter;
            TextureImporterSettings texSettings = new TextureImporterSettings();

            textureImporter.ReadTextureSettings(texSettings);
            #if UNITY_5_5_OR_NEWER
            texSettings.ApplyTextureType(TextureImporterType.Sprite);
            #else
            texSettings.ApplyTextureType(TextureImporterType.Sprite, true);
            #endif
            texSettings.spritePixelsPerUnit = pixelsPerUnit;
            if (Vector2.Distance(pivot, new Vector2(0.5f, 0.5f)) < 0.01f)
            {
                texSettings.spriteAlignment = (int)SpriteAlignment.Center;
                textureImporter.SetTextureSettings(texSettings);
            }
            else
            {
                texSettings.spriteAlignment = (int)SpriteAlignment.Custom;
                textureImporter.SetTextureSettings(texSettings);
                textureImporter.spritePivot = pivot;
            }
            AssetDatabase.ImportAsset(fname, ImportAssetOptions.ForceUpdate);

            Sprite sprite = Resources.Load <Sprite>(rname);

            Undo.RecordObjects(shape.GetUndoObjects().ToArray(),
                               "Convert to Sprite");

            shape.SetAsSprite(sprite, GetDefaultSpriteMaterial());

            // exit the gui routine because otherwise we get annoying errors because
            // we deleted a material and unity still wants to draw it
            EditorGUIUtility.ExitGUI();
        }