GrabPassの使い方

UnityのシェーダーではGrabPassを使うことで、シャーダー内で簡単にスクリーンの絵を取得できて便利です。

使い方は

GrabPass
{
}

と書くだけ。

後は普通のTextureと同じように

sampler2D _GrabTexture
grabPos = ComputeGrabScreenPos(o.pos);
half4 color = tex2Dproj(_GrabTexture, grabPos);

のようにして使えます。

_GrabTextureの名称を変更したい場合は、GrabPass

GrabPass
{
  "_BackgroundTexture"
}

という風に書くと良いようです。

リンク

Unity – Manual: ShaderLab: GrabPass
https://docs.unity3d.com/Manual/SL-GrabPass.html

C#で配列や構造体の初期化方法

C#で使える便利な初期化方法を調べてみました。

配列の初期化

int[] example1 = new int[] { 3, 1, 4, 1, 5 };

ジャグ配列、多次元配列の初期化

int[][] example2 = new int[][] {
  new int[] { 3, 1, 4 },
  new int[] { 1, 5, 9 }
};

int[,] example3 = new int[,] {
  { 3, 1, 4 },
  { 1, 5, 9 }
};

構造体の初期化

public struct Example
{
  public string name;
  public int value;
}
Example example4 = new Example { name = "name", value = 1 };

Example[] example5 = new Example[] {
  new Example { name = "name1", value = 2 },
  new Example { name = "name2", value = 3 }
};

List<T>やDictionary<T>も次のようにして使えるそうです。

List<int> example6 = new List<int> { 3, 1, 4, 1, 5 };

Dictionary<string, int> example7 = new Dictionary<string, int> {
  { "name3", 4 },
  { "name4", 5 }
}

リンク

構造体の使用 (C# プログラミング ガイド) | Microsoft Docs
https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/classes-and-structs/using-structs

better RecalculateNormals

Unityを使っていると、外部からインポートしたFBXファイルのオブジェクトはスムーズに表示されるけれど、スクリプトからMeshvertices/trianglesを設定したオブジェクトはフラットな感じに表示されてしまうことがあります。

normal-solver-1

そういう場合はNormalの計算方法を見直してみると良いそうです。

A better method to recalculate normals in Unity – Part 2 – The Scheming Developer
http://schemingdeveloper.com/2017/03/26/better-method-recalculate-normals-unity-part-2/

normal-solver-2

リンク

Unity – Scripting API: Mesh
https://docs.unity3d.com/ScriptReference/Mesh.html

Unity – Scripting API: Mesh.RecalculateNormals
https://docs.unity3d.com/ScriptReference/Mesh.RecalculateNormals.html