UI Mask override my shaders custom property ?
I made an ui shader with a grayscale switcher,codes are coppied from "UI-Default",then:
Add a property like this:
_GraySwitch ("GraySwitch", Float) = 1
Declare:
fixed _GraySwitch;
In the frag function, after the:
color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
Add the codes:
if(_GraySwitch > 0)
color.rgb = dot(color.rgb, float3(0.3, 0.59, 0.11));
I also created a script to test this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(UnityEngine.UI.Image))]
public class GrayImage : MonoBehaviour {
public bool graySwitch = true;
public Shader grayscaleShader;
UnityEngine.UI.Image image;
void Start ()
{
image = GetComponent<UnityEngine.UI.Image>();
grayscaleShader = Shader.Find("UI/Grayscale");
image.material = new Material(grayscaleShader);
}
void Update ()
{
image.material.SetFloat("_GraySwitch", graySwitch ? 1f : 0f );
}
}
This works fine, but when the image under a parent with "Mask" component, it can't work! After some tests, I found the variable "_GraySwitch" was changed correctly. So, need some help - -
My unity's version is "5.3.1p1"
Answer by yaukey · Jan 20, 2016 at 04:08 PM
You should derive "Image" component such as "CustomImage" by your own, and override the "GetModifiedMaterial" method, this method will return a new material copy which is compatible with mask rendering if there is a "Mask" parent attached. Use the "CustomImage" instead of your "Image".
public class CustomImage : Image
{
public override Material GetModifiedMaterial(Material baseMaterial)
{
Material cModifiedMat = base.GetModifiedMaterial(baseMaterial);
// Do whatever you want with this "cModifiedMat"...
// You can also hold this and process it in your grayscale code.
// ...
return cModifiedMat;
}
}
Be aware that you are responsible for checking if the material of this image is under the "mask" mode.
We use Unity 2017.4.18f1,I found Class Image already have a member variable(named materialForRendering) to provided to do this.Have a nice day : P
Your answer
Follow this Question
Related Questions
Problem with sprite materials/shaders inside a mask 1 Answer
Cover overlay sprites with geometry 0 Answers
Change alpha on material with custom shader 0 Answers
Trying to write a 2d mask shader with stencil 0 Answers
RenderTexture on RawImage not working 2 Answers