うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】単色テクスチャを生成する

   // 白色の64×64のテクスチャをAssets/に作成する
    private static void CreateTexture()
    {
        var texture = CreateTempTexture(64, 64, Color.white);
        // これを呼ばないと色が書き込まれない
        texture.Apply();
        
        System.IO.File.WriteAllBytes(Application.dataPath + "/temp.png", texture.EncodeToPNG());
        // 削除を忘れない
        DestroyImmediate(texture);
        AssetDatabase.Refresh();
    }

    /// <summary>
    /// 特定の色で埋めたテクスチャを取得
    /// </summary>
    private static Texture2D CreateTempTexture(int width, int height, Color defaultColor = default)
    {
        var texture = new Texture2D(width, height, TextureFormat.RGB24, false);
        
        for (int y = 0; y < texture.height; y++)
            for (int x = 0; x < texture.width; x++)
                texture.SetPixel(x, y, defaultColor);

        return texture;
    }

おまけ

パーリンノイズの画像生成
乱数等を入れてないので、毎回同じテクスチャが作成されます

f:id:hacchi_man:20200224030226p:plainf:id:hacchi_man:20200224030226p:plain

   private static void CreatePerlinNoiseTexture(int width, int height)
    {
        var texture = new Texture2D(width, height, TextureFormat.RGB24, false);

        var colorCache = Color.white;
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
            {
                var xCoord = x / (float) width * 5f;
                var yCoord = y / (float) height * 5f;
                colorCache.r = colorCache.g = colorCache.b = Mathf.PerlinNoise(xCoord, yCoord); 
                texture.SetPixel(x, y, colorCache);
            }

        texture.Apply();
        
        System.IO.File.WriteAllBytes(Application.dataPath + "/temp.png", texture.EncodeToPNG());
        DestroyImmediate(texture);
            
        AssetDatabase.Refresh();
    }