(Shader) Get the center of the object ?

Hello everyone,

I just wanted to know if there was any way that I could get the center of the object on which my shader is applied, in pixel coordinates, so I would finally be able to achieve the effect I want :

I’m learning Unity shaders and I would want a shader that has 2 colors, and a range variable from 0.0 to 1.0. Depending on a ratio variable, the object is displayed with Color1 or Color2. (with 0.0, object is full Color1, 0.5, Color1 on the left part and Color2 on the right part, and with 1.0, object is full Color2, you get it !)

I think this is really really simple, so I’m tired of not getting it to work.

Currently I cheated a little with a script that gives me in runtime the middle of the object in pixel coordinate, because I didn’t find anything on the web to do this directly in my shader, but even with that, it doesn’t work and I definitely don’t understand why, so here I am !

My script :

using UnityEngine;

public class Center : MonoBehaviour {

    private MeshRenderer _renderer;

	void Start () {
        _renderer = GetComponent<MeshRenderer>();
	void Update () {
        _renderer.material.SetInt("_Center", (int)Camera.main.WorldToScreenPoint(_renderer.bounds.center).x);

My shader :

Shader "Custom/First" {
	Properties {
		_Color ("Color1", Color) = (1,0,0,1) // Default red
		_Color2 ("Color2", Color) = (0,0,1,1) // Default blue
        _Ratio ("Ratio", Range(0.0, 1.0)) = 0.5
		_Center ("Center", int) = 0
	SubShader {
		Pass {
			Tags { "RenderType" = "Opaque" }
			LOD 200

			#pragma vertex vert             
			#pragma fragment frag

			struct vertInput {
				float4 pos : POSITION;

			struct vertOutput {
				float4 pos : SV_POSITION;

			fixed4 _Color;
			fixed4 _Color2;
			half1 _Ratio;
			half1 _Center;

			vertOutput vert(vertInput input) {
				vertOutput o;
				// Used to switch from the 3D coordinates system (world) to the 2D coordinates system (screen)
				o.pos = mul(UNITY_MATRIX_MVP, input.pos);
				return o;

			half4 frag(vertOutput output) : COLOR {
				// Pixel is rendered in Color1 if we are before the center; _Color2 otherwise
				return _Color * saturate(sign(_Center - output.pos.x)) + _Color2 * saturate(sign(output.pos.x - _Center));
	FallBack "Diffuse"

I take any comment or advice since I’m a very beginner on this.
Thanks a lot for helping ! :slight_smile:
P.S : There is this _Ratio variable in the shader that currently doesn’t anything, because here I’m just trying to get it work with both Color1 and Color2, using the center of the object. That corresponds obviously to a ratio value of 0.5 :slight_smile:

I haven’t found a solution yet !