Hello!
There is a way to serialize matrices into material?
I think i should declare matrix into Properties bloc, but i can’t find any example what exactly i should to write.
Thanks for advance!
You cannot define matrices as Properties in Shaderlab.
But you can pass matrices as uniforms from Code.
You need to attach an accompanying script (C# or JS) to the object(in your scene) or prefab with the material you want to pass a matrix to.
You usually pass them using Update() function - so you can see changes at each frame.
You will be using this matrix as a uniform, which does mean that is bounded to that material instance, not to vertexes.
In CG program in your shader you define:
uniform float4x4 _YourMatrix;
And you pass a value from the accompanying C# script.
The syntax is the following:
this.material.SetMatrix(“_YourMatrix”, yourMatrixDefinedInCode).
If you want to define the Matrix in the Inspector define it as Public in the C# script:
public Matrix4x4 yourMatrixDefinedInCode;
Try to describe in detail: After setting matrix everything is working properly before solutions was rebooted or scene saved. Can I somehow save the matrix into material, possibly using “Custom material editor”? Mayb there is a way to catch the load solutions or save save a scene event , in order to update the matrix?
using UnityEngine;
[ExecuteInEditMode]
public class SetDecalMatr : MonoBehaviour
{
public Transform proj;
public Matrix4x4 mat;
public bool update;
void Awake()
{
renderer.sharedMaterial.SetMatrix("_DecalMatr", mat);
}
void OnEnable()
{
renderer.sharedMaterial.SetMatrix("_DecalMatr", mat);
}
void Update()
{
if(!update)return;
SetMatr();
}
[ContextMenu("set matrix")]
void SetMatr()
{
if(proj==null)return;
mat = proj.worldToLocalMatrix*transform.localToWorldMatrix;
renderer.sharedMaterial.SetMatrix("_DecalMatr", mat);
}
}
Shader "ProjectedDecal"
{
Properties
{
_MainTex ("Texture Image", 2D) = "white" {}
_DecalTex ("DecalTex Image", 2D) = "white" {}
}
SubShader
{
Pass
{
CGPROGRAM
#pragma only_renderers d3d9 gles
#pragma glsl
#pragma vertex vert
#pragma fragment frag
uniform sampler2D _MainTex;
uniform sampler2D _DecalTex;
uniform float4x4 _DecalMatr;
struct vertexInput
{
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
};
struct vertexOutput
{
float4 pos : SV_POSITION;
float3 pTex : TEXCOORD1;
float2 tex : TEXCOORD0;
};
vertexOutput vert(vertexInput input)
{
vertexOutput output;
float4 trasformed = mul(_DecalMatr, input.vertex);
output.pTex = trasformed.xyz+float3(0.5, 0.5, 0);
output.tex = input.texcoord;
output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
return output;
}
float4 frag(vertexOutput input) : COLOR
{
float4 pc = tex2D(_DecalTex, float2(input.pTex));
if(input.pTex.z<-0.5 || input.pTex.z>0.5)
{
pc.a=0;
}
float4 c = tex2D(_MainTex, input.tex);
return lerp(c, pc, pc.a);
}
ENDCG
}
}
}