モチベーションと目標
前回は,Unityにて,C#スクリプト内でゲーム実行時に作成したメッシュをGLSL Shaderを使って描画しました.今回は,その『メッシュにテクスチャを張る』のが目標です.
C#スクリプトを拡張してテクスチャを読み込む
実装手順
OnlineMesh
に付与したmyMesh.cs
を開くmyMesh
をダブルクリックするとVisual Studioが立ち上がり編集できるようになる
- C#を後述する様に変更
- GLSL Shaderを後述する様に変更
Texture
のすぐ右横にある円のマークをクリックしてテクスチャを一覧から選択- ここでは
Default-Particle
テクスチャを利用 - ちなみに,ステップ2で
public Texture2D Texture
を定義したので,OnlineMesh
のInspector > myMesh
内にTexture
が現れる- 詳細は,後述のC#コードを参照のこと
- ここでは
- 最後に,再生ボタンで実行
C#コード
参考:Unity - Scripting API: Material.SetTexture
using System.Collections; using System.Collections.Generic; using UnityEngine; public class myMesh : MonoBehaviour { public Texture2D texture; // Start is called before the first frame update void Start() { MeshFilter mf = GetComponent<MeshFilter>(); Mesh mesh = new Mesh(); mf.mesh = mesh; Vector3[] vertices = new Vector3[4]; vertices[0] = new Vector3(0.0f, 0.0f, 0.0f); vertices[1] = new Vector3(1.0f, 0.0f, 0.0f); vertices[2] = new Vector3(0.0f, 1.0f, 0.0f); vertices[3] = new Vector3(1.0f, 1.0f, 0.0f); mesh.vertices = vertices; int[] indices = new int[6]; indices[0] = 0; indices[1] = 2; indices[2] = 1; indices[3] = 2; indices[4] = 3; indices[5] = 1; mesh.triangles = indices; Vector2[] uv = new Vector2[4]; uv[0] = new Vector2(0, 0); uv[1] = new Vector2(1, 0); uv[2] = new Vector2(0, 1); uv[3] = new Vector2(1, 1); mesh.uv = uv; Renderer renderer = GetComponent<Renderer>(); renderer.material.SetTexture("texSampler", texture); } // Update is called once per frame void Update() { } }
GLSL Shaderコード
Shader "GLSL basic shader" { SubShader{ Pass { GLSLPROGRAM #ifdef VERTEX out vec2 vsTexCoord; void main() { vsTexCoord = gl_MultiTexCoord0.xy; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } #endif #ifdef FRAGMENT uniform sampler2D texSampler; in vec2 vsTexCoord; void main() { gl_FragColor = texture(texSampler, vsTexCoord); } #endif ENDGLSL } } }
描画結果
ちゃんと矩形にテクスチャを張ることができました.目標達成です!