Inheritance: MonoBehaviour
Beispiel #1
0
 // Use this for initialization
 void Start()
 {
     if (side == null)
     {
         side = front;
     }
 }
Beispiel #2
0
        private List <MeshData> GetMeshData(GameObject obj)
        {
            var sprites = obj.GetComponentsInChildren <SpriteRenderer>();

            var outList = new List <MeshData>(sprites.Length);

            for (int i = 0; i < sprites.Length; i++)
            {
                var spriteMesh = new SpriteMesh(sprites[i].sprite);

                Vector2 ctr = obj.transform.TransformPoint(spriteMesh.GetCentroidLocal());
//                UnityEngine.Debug.DrawLine(ctr, ctr + Vector2.up*100, Color.red, 100);

                outList.Add(new MeshData
                {
                    spriteMesh     = spriteMesh,
                    spriteRenderer = sprites[i],
                    centroid       = ctr,
                    sprite         = sprites[i].sprite,
                    gameObject     = sprites[i].gameObject,
                    parentObject   = obj,
                });
            }

            return(outList);
        }
Beispiel #3
0
    public SpriteMesh getMesh(string meshId)
    {
        int        index  = getIndex(meshId);
        SpriteMesh result = index >= 0 ? availableMeshes[index] : null;

        return(result);
    }
Beispiel #4
0
 protected override void OnDraw(SpriteMesh spriteMesh, float x, float y)
 {
     if (sprite != null)
     {
         spriteMesh.AddSprite(sprite, x, y, sprite.SizeX, sprite.SizeY, Color.white);
     }
 }
Beispiel #5
0
    public void BuildMesh()
    {
        if (PrefabUtility.GetPrefabType(gameObject) == PrefabType.None && sprite != null && root != null)
        {
            SkinnedMeshRenderer skinnedMeshRenderer = GetComponent <SkinnedMeshRenderer>();

            CleanUp();
            Mesh mesh = SpriteMesh.CreateSpriteMeshPoly(sprite);
            mesh.name = "Generated Mesh";
            Bone[] bones = root.GetComponentsInChildren <Bone>();
            boneWeights = SpriteMesh.CalculateBoneWeights(transform, bones, mesh);

            skinnedMeshRenderer.rootBone   = root.transform;
            skinnedMeshRenderer.bones      = bones.Select(b => b.transform).ToArray();
            skinnedMeshRenderer.sharedMesh = mesh;

            if (material != null)
            {
                skinnedMeshRenderer.sharedMaterial = material;
            }
            else
            {
                Material mat = new Material(Shader.Find("Sprites/Default"));
                mat.mainTexture = sprite.texture;
                skinnedMeshRenderer.sharedMaterial = mat;
            }

            AssetDatabase.SaveAssets();
        }
    }
Beispiel #6
0
 /// <param name="nodes">all nodes of the hierarchy, in hierarchic order, for updating transforms</param>
 /// <param name="drawSequenceIndices">the indices of the spritenodes in nodes, in draw order</param>
 internal Skeleton(RTNode[] nodes, int[] drawSequenceIndices, Dictionary <string, RTAnimation> animations, Texture2D texture)
 {
     _nodes = nodes;
     _drawSequenceIndices = drawSequenceIndices;
     _animations          = animations ?? throw new ArgumentNullException(nameof(animations));
     _mesh = new SpriteMesh(drawSequenceIndices.Select(idx => nodes[idx].Sprite), texture, BufferMode.Unbuffered);
 }
        public static void Create ()
        {
			if (Selection.activeGameObject != null) {
				GameObject o = Selection.activeGameObject;
				SkinnedMeshRenderer skin = o.GetComponent<SkinnedMeshRenderer>();
				SpriteRenderer spriteRenderer = o.GetComponent<SpriteRenderer>();
				if (skin == null && spriteRenderer != null) {
					Sprite thisSprite = spriteRenderer.sprite;
					SpriteMesh spriteMesh = new SpriteMesh();
					spriteMesh.spriteRenderer = spriteRenderer;
					spriteMesh.CreateSpriteMesh();
					Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);

					// Copy the sprite material
					Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
					spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
					spriteMaterial.mainTexture = spriteTexture;
					string sortLayerName = spriteRenderer.sortingLayerName;
					int sortOrder = spriteRenderer.sortingOrder;
					DestroyImmediate(spriteRenderer);
					Skin2D skin2D = o.AddComponent<Skin2D>();
					skin2D.sprite = thisSprite;
					skin = o.GetComponent<SkinnedMeshRenderer>();
					MeshFilter filter = o.GetComponent<MeshFilter>();
					skin.material = spriteMaterial;

					// Save out the material from the sprite so we have a default material
					if(!Directory.Exists("Assets/Materials")) {
						AssetDatabase.CreateFolder("Assets", "Materials");
						AssetDatabase.Refresh();
					}
					AssetDatabase.CreateAsset(spriteMaterial, "Assets/Materials/" + spriteMaterial.mainTexture.name + ".mat");
					Debug.Log("Created material " + spriteMaterial.mainTexture.name + " for " + skin.gameObject.name);
					skin2D.referenceMaterial = spriteMaterial;
					skin.sortingLayerName = sortLayerName;
					skin.sortingOrder = sortOrder;

					// Create the mesh from the selection
					filter.mesh = (Mesh)Selection.activeObject;
					if (filter.sharedMesh != null && skin.sharedMesh == null) {
						skin.sharedMesh = filter.sharedMesh;
					}
					// Recalculate the bone weights for the new mesh
					skin2D.RecalculateBoneWeights();
				}
				else
				{
					o = new GameObject ("Skin2D");
					Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
					o.AddComponent<Skin2D> ();
				}
			}
			else
			{
				GameObject o = new GameObject ("Skin2D");
                Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                o.AddComponent<Skin2D> ();
			}
        }
Beispiel #8
0
        public void Draw(SpriteMesh spriteMesh)
        {
            Vector3 position = Position;

            spriteMesh.SetZ(depth);

            OnDraw(spriteMesh, position.x, position.y);
        }
Beispiel #9
0
    void changeSpriteMesh(GameObject current, SpriteMesh mesh)
    {
        var spriteMeshInstance = current.GetComponent <SpriteMeshInstance>();
        var spriteMeshRenderer = current.GetComponent <SkinnedMeshRenderer>();

        spriteMeshInstance.spriteMesh = mesh;
        spriteMeshRenderer.sharedMesh = mesh.sharedMesh;
    }
Beispiel #10
0
        /// <summary>
        /// Handles the popup's appearance.
        /// </summary>
        public override void OnGUI(Rect rect)
        {
            GUILayout.Label("New Costume Piece", EditorStyles.boldLabel);

            // Fields for the target, sprite, and skin.
            target = EditorGUILayout.TextField("Bone Target", target);
            sprite = EditorGUILayout.ObjectField("Sprite Mesh", sprite, typeof(SpriteMesh), false) as SpriteMesh;
            isSkin = EditorGUILayout.Toggle("Is Skin?", isSkin);

            // If the sprite is null, do not allow the user to input a new piece.
            EditorGUI.BeginDisabledGroup(sprite == null);

            // If confirm is clicked
            if (GUILayout.Button("Confirm"))
            {
                parent.serializedObject.Update();

                // Get a reference to the parent's skin meshes list.
                SerializedProperty skinMeshes = parent.serializedObject.FindProperty("skinMeshes");

                // Add a new costume piece to the list.
                int index = skinMeshes.arraySize;
                skinMeshes.arraySize++;

                // Get a reference to the newly created costume piece.
                SerializedProperty newPiece = skinMeshes.GetArrayElementAtIndex(index);

                // This enumerator goes through all the properties of a costume piece
                var childEnum = newPiece.GetEnumerator();

                while (childEnum.MoveNext())
                {
                    // Set each costume piece property to the provided property.
                    var current = childEnum.Current as SerializedProperty;

                    if (current.name == "mesh")
                    {
                        current.objectReferenceValue = sprite;
                    }

                    if (current.name == "skinTarget")
                    {
                        current.stringValue = target;
                    }

                    if (current.name == "isSkin")
                    {
                        current.boolValue = isSkin;
                    }
                }

                // Update the costume data object
                parent.serializedObject.ApplyModifiedProperties();
                editorWindow.Close();
            }

            EditorGUI.EndDisabledGroup();
        }
Beispiel #11
0
    public void OnGUI() {
        GUILayout.Label("Sprite", EditorStyles.boldLabel);

        EditorGUI.BeginChangeCheck();
        spriteRenderer = (SpriteRenderer)EditorGUILayout.ObjectField(spriteRenderer, typeof(SpriteRenderer), true);
        if (Selection.activeGameObject != null) {
            GameObject o = Selection.activeGameObject;
            spriteRenderer = o.GetComponent<SpriteRenderer>();
        }
        if (EditorGUI.EndChangeCheck()) {
            polygon = new Vector2[0];
        }

        if (spriteRenderer != null) {
            EditorGUILayout.Separator();

            GUILayout.Label("Simplify", EditorStyles.boldLabel);

            simplify = EditorGUILayout.FloatField("Vertex Dist.", simplify);

            if (GUILayout.Button("Generate Polygon")) {
                Rect r = spriteRenderer.sprite.rect;
                Texture2D tex = spriteRenderer.sprite.texture;
                IBitmap bmp = ArrayBitmap.CreateFromTexture(tex, new Rect(r.x, r.y, r.width, r.height));
                polygon = BitmapHelper.CreateFromBitmap(bmp);
                polygon = SimplifyTools.DouglasPeuckerSimplify(new Vertices(polygon), simplify).ToArray();
            }

            GUILayout.Label("Vertices: " + polygon.Length);

            EditorGUILayout.Separator();

            if (polygon.Length > 0 && GUILayout.Button("Create Mesh")) {
                CreateMesh();
            }

            if (GUILayout.Button("Create Mesh from Sprite")) {
                SpriteMesh spriteMesh = new SpriteMesh();
                spriteMesh.spriteRenderer = spriteRenderer;
                spriteMesh.CreateSpriteMesh();
            }

            EditorGUILayout.Separator();

            if (GUILayout.Button("Create Mesh from Polygon2D Collider")) {
                PolygonCollider2D polygonCollider = spriteRenderer.GetComponent<PolygonCollider2D>();
                if (polygonCollider == null) {
                    polygonCollider = spriteRenderer.gameObject.AddComponent<PolygonCollider2D>();
                }

                PolygonMesh polygonMesh = new PolygonMesh();
                polygonMesh.polygonCollider = polygonCollider;
                polygonMesh.spriteRenderer = spriteRenderer;
                polygonMesh.CreatePolygonMesh();

            }
        }
    }
Beispiel #12
0
    public void SetProperties(SpriteMesh newSpriteMesh, ColorMask newColors)
    {
        materialProperties.Clear();

        SetSpriteMesh(newSpriteMesh);
        SetColors(newColors);

        meshRenderer.SetPropertyBlock(materialProperties);
    }
Beispiel #13
0
    private void InitializeSpriteMesh()
    {
        GameObject obj = new GameObject("SpriteMesh");

        obj.transform.parent = gameObject.transform;

        m_SpriteMesh = (SpriteMesh)obj.AddComponent(typeof(SpriteMesh));
        m_SpriteMesh.Initialize(LAYER, MAX_SPRITE_LAYER);
    }
Beispiel #14
0
    /// <summary>
    /// Start this instance.
    /// </summary>
    private void Start()
    {
        myRenderer.sharedMaterial.mainTexture = defaultTexture;

        if (sMesh == null)
        {
            sMesh = new SpriteMesh(defaultTexture);
        }

        ApplyImageRotationAndSpriteTexture();
        UpdateIdolImage();
    }
        public static void SavePose(Skin skin, Transform root)
        {
            List <SpriteMeshInstance> skins = new List <SpriteMeshInstance>(50);

            root.GetComponentsInChildren <SpriteMeshInstance>(true, skins);

            SerializedObject   skin0s      = new SerializedObject(skin);
            SerializedProperty entriesProp = skin0s.FindProperty("m_SkinEntries");


            skin0s.Update();
            entriesProp.arraySize = skins.Count;

            for (int i = 0; i < skins.Count; i++)
            {
                SpriteMeshInstance spriteMeshInstance = skins[i];

                if (spriteMeshInstance)
                {
                    SerializedProperty element = entriesProp.GetArrayElementAtIndex(i);
                    element.FindPropertyRelative("path").stringValue          = SpriteMeshUtils.GetSpriteMeshPath(root, spriteMeshInstance);
                    element.FindPropertyRelative("skin").objectReferenceValue = spriteMeshInstance.spriteMesh;
                }
            }

            skin0s.ApplyModifiedProperties();
            List <SpriteMesh> faces = new List <SpriteMesh>(50);

            faces.AddRange(root.GetComponentInChildren <SpriteMeshAnimation>().frames);

            SerializedObject   face0s       = new SerializedObject(skin);
            SerializedProperty entriesProp1 = face0s.FindProperty("m_FaceEntries");


            face0s.Update();
            entriesProp1.arraySize = faces.Count;
            for (int i = 0; i < faces.Count; i++)
            {
                SpriteMesh faceMesh = faces[i];

                if (faceMesh)
                {
                    SerializedProperty element = entriesProp1.GetArrayElementAtIndex(i);
                    element.FindPropertyRelative("path").stringValue          = SpriteMeshUtils.GetSpriteMeshPath(root, root.GetComponentInChildren <SpriteMeshAnimation>());
                    element.FindPropertyRelative("skin").objectReferenceValue = faceMesh;
                }
            }



            face0s.ApplyModifiedProperties();
        }
        private static SpriteMesh GenerateSpriteMesh(Sprite sprite)
        {
            SpriteMesh spriteMesh = SpriteMeshUtils.CreateSpriteMesh(sprite);

            SpriteMeshInstance spriteMeshInstance = SpriteMeshUtils.CreateSpriteMeshInstance(spriteMesh, Selection.activeGameObject, true);

            SpriteMeshCache spriteMeshCache = ScriptableObject.CreateInstance <SpriteMeshCache>();

            spriteMeshCache.SetSpriteMesh(spriteMesh, spriteMeshInstance);
            spriteMeshCache.InitFromOutline(0.25f, 0.05f, true, 0.1f, "set outline");
            spriteMeshCache.ApplyChanges();

            return(spriteMesh);
        }
Beispiel #17
0
 public static void Create()
 {
     if (Selection.activeGameObject != null)
     {
         GameObject          o              = Selection.activeGameObject;
         SkinnedMeshRenderer skin           = o.GetComponent <SkinnedMeshRenderer>();
         SpriteRenderer      spriteRenderer = o.GetComponent <SpriteRenderer>();
         if (skin == null && spriteRenderer != null)
         {
             Sprite     thisSprite = spriteRenderer.sprite;
             SpriteMesh spriteMesh = new SpriteMesh();
             spriteMesh.spriteRenderer = spriteRenderer;
             spriteMesh.CreateSpriteMesh();
             Texture2D spriteTexture  = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);
             Material  spriteMaterial = new Material(spriteRenderer.sharedMaterial);
             spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
             spriteMaterial.mainTexture = spriteTexture;
             string sortLayerName = spriteRenderer.sortingLayerName;
             int    sortOrder     = spriteRenderer.sortingOrder;
             DestroyImmediate(spriteRenderer);
             Skin2D skin2D = o.AddComponent <Skin2D>();
             skin2D.sprite = thisSprite;
             skin          = o.GetComponent <SkinnedMeshRenderer>();
             MeshFilter filter = o.GetComponent <MeshFilter>();
             skin.material         = spriteMaterial;
             skin.sortingLayerName = sortLayerName;
             skin.sortingOrder     = sortOrder;
             filter.mesh           = (Mesh)Selection.activeObject;
             if (filter.sharedMesh != null && skin.sharedMesh == null)
             {
                 skin.sharedMesh = filter.sharedMesh;
             }
             // Recalculate the bone weights for the new mesh
             skin2D.RecalculateBoneWeights();
         }
         else
         {
             o = new GameObject("Skin2D");
             Undo.RegisterCreatedObjectUndo(o, "Create Skin2D");
             o.AddComponent <Skin2D> ();
         }
     }
     else
     {
         GameObject o = new GameObject("Skin2D");
         Undo.RegisterCreatedObjectUndo(o, "Create Skin2D");
         o.AddComponent <Skin2D> ();
     }
 }
        public static void Create ()
        {
			if (Selection.activeGameObject != null) {
				GameObject o = Selection.activeGameObject;
				SkinnedMeshRenderer skin = o.GetComponent<SkinnedMeshRenderer>();
				SpriteRenderer spriteRenderer = o.GetComponent<SpriteRenderer>();
				if (skin == null && spriteRenderer != null) {
					Sprite thisSprite = spriteRenderer.sprite;
					SpriteMesh spriteMesh = new SpriteMesh();
					spriteMesh.spriteRenderer = spriteRenderer;
					spriteMesh.CreateSpriteMesh();
					Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);
					Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
					spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
					spriteMaterial.mainTexture = spriteTexture;
					string sortLayerName = spriteRenderer.sortingLayerName;
					int sortOrder = spriteRenderer.sortingOrder;
					DestroyImmediate(spriteRenderer);
					Skin2D skin2D = o.AddComponent<Skin2D>();
					skin2D.sprite = thisSprite;
					skin = o.GetComponent<SkinnedMeshRenderer>();
					MeshFilter filter = o.GetComponent<MeshFilter>();
					skin.material = spriteMaterial;
					skin.sortingLayerName = sortLayerName;
					skin.sortingOrder = sortOrder;
					filter.mesh = (Mesh)Selection.activeObject;
					if (filter.sharedMesh != null && skin.sharedMesh == null) {
						skin.sharedMesh = filter.sharedMesh;
					}
					// Recalculate the bone weights for the new mesh
					skin2D.RecalculateBoneWeights();
				}
				else
				{
					o = new GameObject ("Skin2D");
					Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
					o.AddComponent<Skin2D> ();
				}
			}
			else
			{
				GameObject o = new GameObject ("Skin2D");
                Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                o.AddComponent<Skin2D> ();
			}
        }
Beispiel #19
0
    public void ApplyBodyData(BodySlot slot, SpriteMesh spriteMesh, ColorMask colors)
    {
        if (!slot)
        {
            return;
        }

        SpriteMeshRenderer renderer;

        if (_bodyRendererDict.TryGetValue(slot, out renderer) && renderer)
        {
            renderer.SetProperties(spriteMesh, colors);
        }
        else
        {
            Debug.LogError("Character does not have part for slot: " + slot, this);
        }
    }
Beispiel #20
0
    public void SetSpriteMesh(SpriteMesh newSpriteMesh)
    {
        _spriteMesh = newSpriteMesh;
        if (_spriteMesh)
        {
            enabled = true;
            meshRenderer.enabled = true;

            meshRenderer.sharedMesh = _spriteMesh.sharedMesh;
            materialProperties.SetTexture(_MainTexProperty, _spriteMesh.sprite.texture);
        }
        else
        {
            enabled = false;
            meshRenderer.enabled = false;

            meshRenderer.sharedMesh = null;
            materialProperties.SetTexture(_MainTexProperty, Texture2D.whiteTexture);
        }
    }
Beispiel #21
0
    public void Refresh()
    {
        if (Application.isPlaying)
        {
            transform.position = new Vector3(-Screen.width / 2, Screen.height / 2, 0);
        }

        if (SpriteSheet == null)
        {
            return;
        }

        if (spriteMesh == null)
        {
            spriteMesh = new SpriteMesh();
        }

        if (scale != lastScale || dirty)
        {
            dirty = false;

            spriteMesh.BeginCalculateSize();
            DrawMesh();
            SpriteMeshInfo meshInfo = spriteMesh.End();

            spriteMesh.Begin(meshInfo);
            DrawMesh();
            spriteMesh.End();

            spriteMesh.Apply();
            GetComponent <MeshFilter>().sharedMesh = spriteMesh.Mesh;

            lastScale = scale;
        }

        lastScreenWidth  = Screen.width;
        lastScreenHeight = Screen.height;
    }
Beispiel #22
0
        public static void Create ()
        {
			if (Selection.activeGameObject != null) {
				GameObject o = Selection.activeGameObject;
				SkinnedMeshRenderer skin = o.GetComponent<SkinnedMeshRenderer>();
				SpriteRenderer spriteRenderer = o.GetComponent<SpriteRenderer>();
				if (skin == null && spriteRenderer != null) {
					Sprite thisSprite = spriteRenderer.sprite;
					SpriteMesh spriteMesh = new SpriteMesh();
					spriteMesh.spriteRenderer = spriteRenderer;
					spriteMesh.CreateSpriteMesh();
					Texture2D spriteTexture = UnityEditor.Sprites.DataUtility.GetSpriteTexture(spriteRenderer.sprite, false);
					Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
					spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
					spriteMaterial.mainTexture = spriteTexture;
					DestroyImmediate(spriteRenderer);
					Skin2D skin2D = o.AddComponent<Skin2D>();
					skin2D.sprite = thisSprite;
					skin = o.GetComponent<SkinnedMeshRenderer>();
					MeshFilter filter = o.GetComponent<MeshFilter>();
					skin.material = spriteMaterial;
					filter.mesh = (Mesh)Selection.activeObject;
					if (filter.sharedMesh != null && skin.sharedMesh == null) {
						skin.sharedMesh = filter.sharedMesh;
					}
					Skeleton skeleton = o.transform.root.GetComponent<Skeleton>();
					if (skeleton != null)
					{
						// Generate the mesh and calculate the weights if the root transform has a skeleton
						skeleton.CalculateWeights();
						// Debug.Log("Calculated weights for " + o.name);

						// Try to initialize the parent bone to this skin
						Bone bone = o.transform.parent.GetComponent<Bone>();
						if (bone != null)
						{
							Mesh m = skin.sharedMesh.Clone();
							List<BoneWeight> weights = m.boneWeights.ToList();

							for (int i = 0; i < m.vertices.Length; i++) {
								BoneWeight bw = weights[i];
								bw = bw.SetWeight(bone.index, 1);
								weights[i] = bw.Clone();
							}

							skin.sharedMesh.boneWeights = weights.ToArray();
							EditorUtility.SetDirty(skin.gameObject);
							if (PrefabUtility.GetPrefabType(skin.gameObject) != PrefabType.None) {
								AssetDatabase.SaveAssets();
							}
						}
					}
				}
				else
				{
					o = new GameObject ("Skin2D");
					Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
					o.AddComponent<Skin2D> ();
				}
			}
			else
			{
				GameObject o = new GameObject ("Skin2D");
                Undo.RegisterCreatedObjectUndo (o, "Create Skin2D");
                o.AddComponent<Skin2D> ();
			}
        }
    public void OnGUI()
    {
        GUILayout.Label("Sprite", EditorStyles.boldLabel);

        EditorGUI.BeginChangeCheck();
        spriteRenderer = (SpriteRenderer)EditorGUILayout.ObjectField(spriteRenderer, typeof(SpriteRenderer), true);
        if (Selection.activeGameObject != null) {
            GameObject o = Selection.activeGameObject;
            spriteRenderer = o.GetComponent<SpriteRenderer>();
        }
        if (EditorGUI.EndChangeCheck()) {
            polygon = new Vector2[0];
        }

        if (spriteRenderer != null) {
            EditorGUILayout.Separator();

            GUILayout.Label("Simplify", EditorStyles.boldLabel);

            simplify = EditorGUILayout.FloatField("Vertex Dist.", simplify);

            if (GUILayout.Button("Generate Polygon")) {
                Rect r = spriteRenderer.sprite.rect;
                Texture2D tex = spriteRenderer.sprite.texture;
                IBitmap bmp = ArrayBitmap.CreateFromTexture(tex, new Rect(r.x, r.y, r.width, r.height));
                polygon = BitmapHelper.CreateFromBitmap(bmp);
                polygon = SimplifyTools.DouglasPeuckerSimplify(new Vertices(polygon), simplify).ToArray();
                EditorUtility.SetDirty(this);
            }

            GUILayout.Label("Vertices: " + polygon.Length);

            EditorGUILayout.Separator();

            if (polygon.Length > 0 && GUILayout.Button("Create Mesh")) {
                CreateMesh();
                EditorUtility.SetDirty(this);
            }

            if (GUILayout.Button("Create Mesh from Sprite")) {
                SpriteMesh spriteMesh = new SpriteMesh();
                spriteMesh.spriteRenderer = spriteRenderer;
                spriteMesh.CreateSpriteMesh();
                EditorUtility.SetDirty(this);
            }

            EditorGUILayout.Separator();

            if (GUILayout.Button("Create Mesh from Polygon2D Collider")) {
                PolygonCollider2D polygonCollider = spriteRenderer.GetComponent<PolygonCollider2D>();
                if (polygonCollider == null) {
                    polygonCollider = spriteRenderer.gameObject.AddComponent<PolygonCollider2D>();
                }

                PolygonMesh polygonMesh = new PolygonMesh();
                polygonMesh.polygonCollider = polygonCollider;
                polygonMesh.spriteRenderer = spriteRenderer;
                polygonMesh.CreatePolygonMesh();
                EditorUtility.SetDirty(this);
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Create and Edit a Custom Polygon", EditorStyles.boldLabel);
            handleScale = EditorGUILayout.FloatField("Handle Size", handleScale);
            handleColor = EditorGUILayout.ColorField("Handle Color", handleColor);
            polyColor = EditorGUILayout.ColorField("Poly Color", polyColor);

            EditorGUILayout.Separator();

            GUILayout.Label("Ctrl + Click to Add Point, Shift + Click to Add Mid Point, Alt + Click to Remove Points", EditorStyles.whiteLabel);

            EditorGUILayout.Separator();

            if (GUILayout.Button("Create and Edit Polygon")) {
                CreatePolygon();
                EditorUtility.SetDirty(this);
            }

            EditorUtility.SetSelectedRenderState(spriteRenderer, EditorSelectedRenderState.Hidden);

            if (GUILayout.Button("Update Custom Mesh")) {
                if (spriteRenderer != null) UpdateMesh();
                EditorUtility.SetDirty(this);
            }

            if (GUILayout.Button("Save Custom Mesh")) {
                if (spriteRenderer != null) SaveMesh();
            }

            if (GUI.changed) {
                UpdateMesh();
                EditorUtility.SetDirty(this);
            }

            GUILayout.Label("Subdivide Mesh", EditorStyles.boldLabel);

            string[] subdivide = { "0", "1", "2", "3" };

            divisions = EditorGUILayout.Popup("Subdivisions", divisions, subdivide);

            if (GUILayout.Button("Subdivide Mesh")) {
                if (spriteRenderer != null && mesh != null) SubdivideMesh(divisions);
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Load Custom Mesh to Edit", EditorStyles.boldLabel);

            GUILayout.Label("Adding or Deleting points Re-Triangulates Mesh", EditorStyles.whiteLabel);

            EditorGUILayout.Separator();
            customLoadMesh = (Mesh)EditorGUILayout.ObjectField(customLoadMesh, typeof(Mesh), true);

            if (GUILayout.Button("Load Custom Mesh")) {
                if (spriteRenderer != null && customLoadMesh != null) {
                    LoadMesh(customLoadMesh);
                }
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Combine Meshes", EditorStyles.boldLabel);

            GUILayout.Label("Avoid Combining Complex Meshes, results will vary", EditorStyles.whiteLabel);

            EditorGUILayout.Separator();
            combineMesh = (Mesh)EditorGUILayout.ObjectField(combineMesh, typeof(Mesh), true);

            if (GUILayout.Button("Combine Meshes")) {
                if (spriteRenderer != null) CombineMesh();
            }
        }
    }
Beispiel #24
0
    public void OnGUI()
    {
        GUILayout.Label("Sprite", EditorStyles.boldLabel);

        EditorGUI.BeginChangeCheck();
        spriteRenderer = (SpriteRenderer)EditorGUILayout.ObjectField(spriteRenderer, typeof(SpriteRenderer), true);
        if (Selection.activeGameObject != null)
        {
            GameObject o = Selection.activeGameObject;
            spriteRenderer = o.GetComponent <SpriteRenderer>();
        }
        if (EditorGUI.EndChangeCheck())
        {
            polygon = new Vector2[0];
        }

        if (spriteRenderer != null)
        {
            EditorGUILayout.Separator();

            GUILayout.Label("Simplify", EditorStyles.boldLabel);

            simplify = EditorGUILayout.FloatField("Vertex Dist.", simplify);

            if (GUILayout.Button("Generate Polygon"))
            {
                Rect      r   = spriteRenderer.sprite.rect;
                Texture2D tex = spriteRenderer.sprite.texture;
                IBitmap   bmp = ArrayBitmap.CreateFromTexture(tex, new Rect(r.x, r.y, r.width, r.height));
                polygon = BitmapHelper.CreateFromBitmap(bmp);
                polygon = SimplifyTools.DouglasPeuckerSimplify(new Vertices(polygon), simplify).ToArray();
                EditorUtility.SetDirty(this);
            }

            GUILayout.Label("Vertices: " + polygon.Length);

            EditorGUILayout.Separator();

            if (polygon.Length > 0 && GUILayout.Button("Create Mesh"))
            {
                CreateMesh();
                EditorUtility.SetDirty(this);
            }

            if (GUILayout.Button("Create Mesh from Sprite"))
            {
                SpriteMesh spriteMesh = new SpriteMesh();
                spriteMesh.spriteRenderer = spriteRenderer;
                spriteMesh.CreateSpriteMesh();
                EditorUtility.SetDirty(this);
            }

            EditorGUILayout.Separator();

            if (GUILayout.Button("Create Mesh from Polygon2D Collider"))
            {
                PolygonCollider2D polygonCollider = spriteRenderer.GetComponent <PolygonCollider2D>();
                if (polygonCollider == null)
                {
                    polygonCollider = spriteRenderer.gameObject.AddComponent <PolygonCollider2D>();
                }

                PolygonMesh polygonMesh = new PolygonMesh();
                polygonMesh.polygonCollider = polygonCollider;
                polygonMesh.spriteRenderer  = spriteRenderer;
                polygonMesh.CreatePolygonMesh();
                EditorUtility.SetDirty(this);
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Create and Edit a Custom Polygon", EditorStyles.boldLabel);
            handleScale = EditorGUILayout.FloatField("Handle Size", handleScale);
            handleColor = EditorGUILayout.ColorField("Handle Color", handleColor);
            polyColor   = EditorGUILayout.ColorField("Poly Color", polyColor);

            EditorGUILayout.Separator();

            GUILayout.Label("Ctrl + Click to Add Point, Shift + Click to Add Mid Point, Alt + Click to Remove Points", EditorStyles.whiteLabel);

            EditorGUILayout.Separator();

            if (GUILayout.Button("Create and Edit Polygon"))
            {
                CreatePolygon();
                EditorUtility.SetDirty(this);
            }

            EditorUtility.SetSelectedWireframeHidden(spriteRenderer, true);

            if (GUILayout.Button("Update Custom Mesh"))
            {
                if (spriteRenderer != null)
                {
                    UpdateMesh();
                }
                EditorUtility.SetDirty(this);
            }

            if (GUILayout.Button("Save Custom Mesh"))
            {
                if (spriteRenderer != null)
                {
                    SaveMesh();
                }
            }

            if (GUI.changed)
            {
                UpdateMesh();
                EditorUtility.SetDirty(this);
            }

            GUILayout.Label("Subdivide Mesh", EditorStyles.boldLabel);

            string[] subdivide = { "0", "1", "2", "3" };

            divisions = EditorGUILayout.Popup("Subdivisions", divisions, subdivide);

            if (GUILayout.Button("Subdivide Mesh"))
            {
                if (spriteRenderer != null && mesh != null)
                {
                    SubdivideMesh(divisions);
                }
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Load Custom Mesh to Edit", EditorStyles.boldLabel);

            GUILayout.Label("Adding or Deleting points Re-Triangulates Mesh", EditorStyles.whiteLabel);

            EditorGUILayout.Separator();
            customLoadMesh = (Mesh)EditorGUILayout.ObjectField(customLoadMesh, typeof(Mesh), true);

            if (GUILayout.Button("Load Custom Mesh"))
            {
                if (spriteRenderer != null && customLoadMesh != null)
                {
                    LoadMesh(customLoadMesh);
                }
            }

            EditorGUILayout.Separator();

            GUILayout.Label("Combine Meshes", EditorStyles.boldLabel);

            GUILayout.Label("Avoid Combining Complex Meshes, results will vary", EditorStyles.whiteLabel);

            EditorGUILayout.Separator();
            combineMesh = (Mesh)EditorGUILayout.ObjectField(combineMesh, typeof(Mesh), true);

            if (GUILayout.Button("Combine Meshes"))
            {
                if (spriteRenderer != null)
                {
                    CombineMesh();
                }
            }
        }
    }
        void uploadVertices(IDeviceContext ic, Span <sDrawCall> drawCallsSpan)
        {
            ReadOnlySpan <int> baseVertices = buffersLayout.baseVertices;

            using (var mapped = resources.getVertexBuffer().map <sVertexWithId>(ic, buffersLayout.vertexBufferSize))
            {
                Span <sVertexWithId> span = mapped.span;

                for (int i = 0; i < drawCallsSpan.Length; i++)
                {
                    int bv = baseVertices[i];
                    if (bv < 0)
                    {
                        continue;                           // Empty draw call, i.e. completely clipped out
                    }
                    Span <sVertexWithId> dest = span.Slice(bv);

                    ref var dc = ref drawCallsSpan[i];
                    uint    id = VertexID.vertex(i);
                    int     sn = dc.order.sn;
                    if (sn >= 0)
                    {
                        drawMeshes.meshes[sn].mesh.mesh.copyVertices(dest, id);
                        continue;
                    }
                    sn = -sn - 1;

                    if (dc.drawCall.mesh == eMesh.SpriteRectangle)
                    {
                        Rect rc = drawMeshes.spriteCommands[sn].rect;
                        SpriteMesh.writeVertices(dest, ref rc, id);
                        continue;
                    }

                    if (dc.drawCall.isText)
                    {
                        var           text = drawMeshes.textCommands[sn];
                        sMeshDataSize mds;
                        if (text.consoleWidth.HasValue)
                        {
                            mds = text.font.renderConsole(dest, id, text.text, text.rectangle.topLeft, text.textRendering, text.consoleWidth.Value);
                        }
                        else
                        {
                            mds = text.font.renderBlock(dest, id, text.text, ref text.rectangle, text.textRendering);
                        }

                        Debug.Assert(mds.vertices <= text.meshDataSize.vertices && mds.triangles <= text.meshDataSize.triangles);
                        // Store the actual count of triangles written.
                        // uploadIndices function needs it later, to fill unused portion of the index buffer with UINT_MAX (32 bit IB) or 0xFFFF (16 bit IB) discarding the data.
                        // Technically that's wasted GPU bandwidth, however:
                        // (a) Not much of it, as normal text only contains a few of these soft hyphens and ligatures.
                        // (b) Saves substantial amount of resources allowing to generate the complete mesh with a single pass over the glyphs.
                        // With exact-sized buffers, we would have to build the complete text mesh in managed memory, then copy to GPU.
                        // Current implementation only buffers 1 word for left aligned blocks, or 1 line for middle or right aligned blocks, or nothing at all for single-line text. The vertices go straight to mapped GPU verftex buffer.
                        text.actualTriangles        = mds.triangles;
                        drawMeshes.textCommands[sn] = text;

                        // dbgPrintGlyphVertices( dest );
                        continue;
                    }

                    sDrawRectCommand cmd = drawMeshes.rectCommands[sn];
                    if (cmd.strokeWidth.HasValue)
                    {
                        RectangleMesh.strokedVertices(dest, id, ref cmd.rect, cmd.strokeWidth.Value);
                    }
                    else
                    {
                        RectangleMesh.filledVertices(dest, id, ref cmd.rect);
                    }
                }
            }
Beispiel #26
0
 public static void RebuildBlendShapes(SpriteMesh spriteMesh)
 {
     RebuildBlendShapes(spriteMesh, spriteMesh.sharedMesh);
 }
Beispiel #27
0
        public static void RebuildBlendShapes(SpriteMesh spriteMesh, Mesh mesh)
        {
            if (!mesh)
            {
                return;
            }

            if (!spriteMesh)
            {
                return;
            }

            BlendShape[] blendShapes = null;

            //SpriteMeshData spriteMeshData = LoadSpriteMeshData(spriteMesh);

            //if (spriteMeshData)
            {
                //blendShapes = spriteMeshData.blendshapes;
            }

            if (spriteMesh.sharedMesh.vertexCount != mesh.vertexCount)
            {
                return;
            }

            if (blendShapes != null)
            {
#if !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
                List <string> blendShapeNames = new List <string>();

                mesh.ClearBlendShapes();

                Vector3[] from = mesh.vertices;

                for (int i = 0; i < blendShapes.Length; i++)
                {
                    BlendShape blendshape = blendShapes[i];

                    if (blendshape)
                    {
                        string blendShapeName = blendshape.name;

                        if (blendShapeNames.Contains(blendShapeName))
                        {
                            Debug.LogWarning("Found repeated BlendShape name '" + blendShapeName + "' in SpriteMesh: " + spriteMesh.name);
                        }
                        else
                        {
                            blendShapeNames.Add(blendShapeName);

                            for (int j = 0; j < blendshape.frames.Length; j++)
                            {
                                BlendShapeFrame l_blendshapeFrame = blendshape.frames[j];

                                if (l_blendshapeFrame && from.Length == l_blendshapeFrame.vertices.Length)
                                {
                                    //Vector3[] deltaVertices = GetDeltaVertices(from, l_blendshapeFrame.vertices);

                                    //mesh.AddBlendShapeFrame(blendShapeName, l_blendshapeFrame.weight, deltaVertices, null, null);
                                }
                            }
                        }
                    }
                }

                mesh.UploadMeshData(false);

                //EditorUtility.SetDirty(mesh);

                //HideMaterials(spriteMesh);
#endif
            }
        }
        private static ReconstructData GetReconstructData(PsdDocument psdDoc, string psdPath, Vector2 documentPivot,
                                                          ImportUserData importSettings, ImportLayerData reconstructRoot)
        {
            // Get the texture import setting of the PSD
            TextureImporter         psdUnitySettings = (TextureImporter)AssetImporter.GetAtPath(psdPath);
            TextureImporterSettings psdUnityImport   = new TextureImporterSettings();

            psdUnitySettings.ReadTextureSettings(psdUnityImport);

            Vector2         docSize = new Vector2(psdDoc.Width, psdDoc.Height);
            ReconstructData data    = new ReconstructData(docSize, documentPivot, psdUnitySettings.spritePixelsPerUnit);

            reconstructRoot.Iterate(
                layerCallback: layer =>
            {
                if (layer.import == false)
                {
                    return;
                }

                var psdLayer = GetPsdLayerByIndex(psdDoc, layer.indexId);

                Rect layerBounds = new Rect()
                {
                    xMin = psdLayer.Left,
                    xMax = psdLayer.Right,
                    yMin = psdDoc.Height - psdLayer.Bottom,
                    yMax = psdDoc.Height - psdLayer.Top
                };
                data.layerBoundsIndex.Add(layer.indexId, layerBounds);

                string layerDir;
                string layerPath = GetFilePath(psdLayer, importSettings, "png", out layerDir);

                string layerMeshDir;
                string layerMeshPath = GetFilePath(psdLayer, importSettings, "asset", out layerMeshDir);

                Sprite layerSprite         = AssetDatabase.LoadAssetAtPath <Sprite>(layerPath);
                SpriteMesh layerSpriteMesh = AssetDatabase.LoadAssetAtPath <SpriteMesh>(layerMeshPath);

                if (layerSprite == null)
                {
                    layerSprite = ImportLayer(psdDoc, importSettings, layer, psdUnityImport);
                }

                if (layerSpriteMesh == null && importSettings.GenerateSpriteMesh)
                {
                    layerSpriteMesh = GenerateSpriteMesh(layerSprite);
                }

                Vector2 spriteAnchor = Vector2.zero;

                if (layerSprite != null)
                {
                    TextureImporter layerImporter         = (TextureImporter)AssetImporter.GetAtPath(layerPath);
                    TextureImporterSettings layerSettings = new TextureImporterSettings();
                    layerImporter.ReadTextureSettings(layerSettings);

                    if (layerSettings.spriteAlignment == (int)SpriteAlignment.Custom)
                    {
                        spriteAnchor = layerSettings.spritePivot;
                    }
                    else
                    {
                        spriteAnchor = AlignmentToPivot((SpriteAlignment)layerSettings.spriteAlignment);
                    }
                }

                data.AddSprite(layer.indexId, layerSprite, spriteAnchor);

                if (importSettings.GenerateSpriteMesh)
                {
                    data.AddSpriteMesh(layer.indexId, layerSpriteMesh);
                }
            },
                canEnterGroup: checkGroup => checkGroup.import
                );

            return(data);
        }
Beispiel #29
0
 public void AddSpriteMesh(int[] layerIdx, SpriteMesh spriteMesh)
 {
     spriteMeshIndex.Add(layerIdx, spriteMesh);
 }
 public void spriteRect(Span <uint> destSpan, int baseVertex) =>
 SpriteMesh.writeIndices(destSpan, baseVertex);
Beispiel #31
0
    public void OnGUI()
    {
        GUILayout.Label("Sprite", EditorStyles.boldLabel);

        EditorGUI.BeginChangeCheck();
        spriteRenderer = (SpriteRenderer)EditorGUILayout.ObjectField(spriteRenderer, typeof(SpriteRenderer), true);
        if (Selection.activeGameObject != null)
        {
            GameObject o = Selection.activeGameObject;
            spriteRenderer = o.GetComponent <SpriteRenderer>();
        }
        if (EditorGUI.EndChangeCheck())
        {
            polygon = new Vector2[0];
        }

        if (spriteRenderer != null)
        {
            EditorGUILayout.Separator();

            GUILayout.Label("Simplify", EditorStyles.boldLabel);

            simplify = EditorGUILayout.FloatField("Vertex Dist.", simplify);

            if (GUILayout.Button("Generate Polygon"))
            {
                Rect      r   = spriteRenderer.sprite.rect;
                Texture2D tex = spriteRenderer.sprite.texture;
                IBitmap   bmp = ArrayBitmap.CreateFromTexture(tex, new Rect(r.x, r.y, r.width, r.height));
                polygon = BitmapHelper.CreateFromBitmap(bmp);
                polygon = SimplifyTools.DouglasPeuckerSimplify(new Vertices(polygon), simplify).ToArray();
            }

            GUILayout.Label("Vertices: " + polygon.Length);

            EditorGUILayout.Separator();

            if (polygon.Length > 0 && GUILayout.Button("Create Mesh"))
            {
                CreateMesh();
            }

            if (GUILayout.Button("Create Mesh from Sprite"))
            {
                SpriteMesh spriteMesh = new SpriteMesh();
                spriteMesh.spriteRenderer = spriteRenderer;
                spriteMesh.CreateSpriteMesh();
            }

            EditorGUILayout.Separator();

            if (GUILayout.Button("Create Mesh from Polygon2D Collider"))
            {
                PolygonCollider2D polygonCollider = spriteRenderer.GetComponent <PolygonCollider2D>();
                if (polygonCollider == null)
                {
                    polygonCollider = spriteRenderer.gameObject.AddComponent <PolygonCollider2D>();
                }

                PolygonMesh polygonMesh = new PolygonMesh();
                polygonMesh.polygonCollider = polygonCollider;
                polygonMesh.spriteRenderer  = spriteRenderer;
                polygonMesh.CreatePolygonMesh();
            }
        }
    }
Beispiel #32
0
 // Use this for initialization
 void Start()
 {
     spr = new SpriteMesh(texture);
     GenerateSpriteMesh();
 }
Beispiel #33
0
 public SpriteTiledMesh()
 {
     brush      = new MeshBrush();
     spriteMesh = new SpriteMesh();
 }
Beispiel #34
0
    public static void Create()
    {
        if (Selection.activeGameObject != null)
        {
            GameObject          o              = Selection.activeGameObject;
            SkinnedMeshRenderer skin           = o.GetComponent <SkinnedMeshRenderer>();
            SpriteRenderer      spriteRenderer = o.GetComponent <SpriteRenderer>();
            if (skin == null && spriteRenderer != null)
            {
                Sprite thisSprite = spriteRenderer.sprite;
                SpriteMesh.CreateSpriteMeshAsset(spriteRenderer.transform, thisSprite);
                Texture2D spriteTexture  = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);
                Material  spriteMaterial = new Material(spriteRenderer.sharedMaterial);
                spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
                spriteMaterial.mainTexture = spriteTexture;
                DestroyImmediate(spriteRenderer);
                Skin2D skin2D = o.AddComponent <Skin2D>();
                skin2D.sprite = thisSprite;
                skin          = o.GetComponent <SkinnedMeshRenderer>();
                MeshFilter filter = o.GetComponent <MeshFilter>();
                skin.material = spriteMaterial;
                filter.mesh   = (Mesh)Selection.activeObject;
                if (filter.sharedMesh != null && skin.sharedMesh == null)
                {
                    skin.sharedMesh = filter.sharedMesh;
                }
                Skeleton skeleton = o.transform.root.GetComponent <Skeleton>();
                if (skeleton != null)
                {
                    // Generate the mesh and calculate the weights if the root transform has a skeleton
                    skeleton.CalculateWeights(true);
                    // Debug.Log("Calculated weights for " + o.name);

                    // Try to initialize the parent bone to this skin
                    Bone bone = o.transform.parent.GetComponent <Bone>();
                    if (bone != null)
                    {
                        Mesh m = skin.sharedMesh.Clone();
                        List <BoneWeight> weights = m.boneWeights.ToList();

                        for (int i = 0; i < m.vertices.Length; i++)
                        {
                            BoneWeight bw = weights[i];
                            bw         = bw.SetWeight(bone.index, 1);
                            weights[i] = bw.Clone();
                        }

                        skin.sharedMesh.boneWeights = weights.ToArray();
                        EditorUtility.SetDirty(skin.gameObject);
                        if (PrefabUtility.GetPrefabType(skin.gameObject) != PrefabType.None)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                }
            }
            else
            {
                o = new GameObject("Skin2D");
                Undo.RegisterCreatedObjectUndo(o, "Create Skin2D");
                o.AddComponent <Skin2D> ();
            }
        }
        else
        {
            GameObject o = new GameObject("Skin2D");
            Undo.RegisterCreatedObjectUndo(o, "Create Skin2D");
            o.AddComponent <Skin2D> ();
        }
    }
Beispiel #35
0
    public static void Create()
    {
        if (Selection.activeGameObject != null)
        {
            GameObject          o              = Selection.activeGameObject;
            SkinnedMeshRenderer skin           = o.GetComponent <SkinnedMeshRenderer>();
            SpriteRenderer      spriteRenderer = o.GetComponent <SpriteRenderer>();
            if (skin == null && spriteRenderer != null)
            {
                Sprite     thisSprite = spriteRenderer.sprite;
                SpriteMesh spriteMesh = new SpriteMesh();
                spriteMesh.spriteRenderer = spriteRenderer;
                spriteMesh.CreateSpriteMesh();
                Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(spriteRenderer.sprite, false);

                // Copy the sprite material
                Material spriteMaterial = new Material(spriteRenderer.sharedMaterial);
                spriteMaterial.CopyPropertiesFromMaterial(spriteRenderer.sharedMaterial);
                spriteMaterial.mainTexture = spriteTexture;
                string sortLayerName = spriteRenderer.sortingLayerName;
                int    sortOrder     = spriteRenderer.sortingOrder;
                DestroyImmediate(spriteRenderer);
                Skin2D skin2D = o.AddComponent <Skin2D>();
                skin2D.sprite = thisSprite;
                skin          = o.GetComponent <SkinnedMeshRenderer>();
                MeshFilter filter = o.GetComponent <MeshFilter>();
                skin.material = spriteMaterial;

                // Save out the material from the sprite so we have a default material
                if (!Directory.Exists("Assets/Materials"))
                {
                    AssetDatabase.CreateFolder("Assets", "Materials");
                    AssetDatabase.Refresh();
                }
                AssetDatabase.CreateAsset(spriteMaterial, "Assets/Materials/" + spriteMaterial.mainTexture.name + ".mat");
                Debug.Log("Created material " + spriteMaterial.mainTexture.name + " for " + skin.gameObject.name);
                skin2D.referenceMaterial = spriteMaterial;
                skin.sortingLayerName    = sortLayerName;
                skin.sortingOrder        = sortOrder;

                // Create the mesh from the selection
                filter.mesh = (Mesh)Selection.activeObject;
                if (filter.sharedMesh != null && skin.sharedMesh == null)
                {
                    skin.sharedMesh = filter.sharedMesh;
                }
                // Recalculate the bone weights for the new mesh
                skin2D.RecalculateBoneWeights();
            }
            else
            {
                o = new GameObject("Skin2D");
                Undo.RegisterCreatedObjectUndo(o, "Create Skin2D");
                o.AddComponent <Skin2D> ();
            }
        }
        else
        {
            GameObject o = new GameObject("Skin2D");
            Undo.RegisterCreatedObjectUndo(o, "Create Skin2D");
            o.AddComponent <Skin2D> ();
        }
    }