【UnityEditor】创建并保存 Texture图片、Mesh网格

 创建保存Texture:

    private void CreateSampleSprite()
    {
        int minRadius = 64;
        int maxRadius = 128;

        //图片尺寸
        int spriteSize = maxRadius * 2;
        //创建Texture2D
        Texture2D texture2D = new Texture2D(spriteSize,spriteSize);
        //图片中心像素点坐标
        Vector2 centerPixel = new Vector2(maxRadius,maxRadius);
        //遍历像素点
        Vector2 tempPixel;
        float tempDis;
        for(int x = 0; x < spriteSize; x++)
        {
            for(int y = 0; y < spriteSize; y++)
            {
                //以中心作为起点,获取像素点向量
                tempPixel.x = x - centerPixel.x;
                tempPixel.y = y - centerPixel.y;
                //是否在半径范围内
                tempDis = tempPixel.magnitude;
                if(tempDis >= minRadius && tempDis <= maxRadius)
                    texture2D.SetPixel(x,y,Color.red);
                else
                    texture2D.SetPixel(x,y,Color.white);
            }
        }
        texture2D.Apply();
        //保存图片
        byte[] dataBytes = texture2D.EncodeToPNG();
        string savePath = Application.dataPath + "/SampleCircle.png";
        FileStream fileStream = File.Open(savePath,FileMode.OpenOrCreate);
        fileStream.Write(dataBytes,0,dataBytes.Length);
        fileStream.Close();
        UnityEditor.AssetDatabase.SaveAssets();
        UnityEditor.AssetDatabase.Refresh();
    }

 创建保存Mesh:

    private void CreateSampleMesh()
    {
        float halfWidth = 50;
        float halfHeight = 50;

        Vector3[] vertices = new Vector3[4];
        vertices[0] = new Vector3(-halfWidth,0,-halfHeight);
        vertices[1] = new Vector3(-halfWidth,0,halfHeight);
        vertices[2] = new Vector3(halfWidth,0,halfHeight);
        vertices[3] = new Vector3(halfWidth,0,-halfHeight);

        int[] triangles = new int[6];
        triangles[0] = 0;
        triangles[1] = 1;
        triangles[2] = 3;
        triangles[3] = 3;
        triangles[4] = 1;
        triangles[5] = 2;

        Mesh newMesh = new Mesh();
        newMesh.vertices = vertices;
        newMesh.triangles = triangles;
        newMesh.name = "SampleMesh";

        string savePath = "Assets/SampleMesh.asset";
        UnityEditor.AssetDatabase.CreateAsset(newMesh,savePath);
        UnityEditor.AssetDatabase.SaveAssets();
        UnityEditor.AssetDatabase.Refresh();
    }

猜你喜欢

转载自blog.csdn.net/qq_39108767/article/details/120003794