Fade Material's Transparency Based on Distance

Okay, so I’ve been at this for hours now and still no luck. Thought I’d see if the pros here could help me out :slight_smile:

So I have everything working correctly except it’s opposite:

dist = Vector3.Distance(transform.position, other.position);
	renderer.material.color.a = dist * .02;

It fades the material when I get closer and then unfades it as I get further away (opposite effect).

How can I fix this? I tried using -Vectot3.Distance and I get some crazy distance number. This is tough because Unity is limited with their scripting references and all they have is Vector3.Distance. Is there another way I can do this? Any help or guidance would be much appreciated and I’ll be sure to give an answered question if you can help me get this working. Thanks

Alpha = 0 means transparent, while alpha = 1 means solid. You could use something like this:

var solidDistance: float = 5.0; // max distance to be 100% solid
dist = Vector3.Distance(transform.position, other.position);
if (dist < solidDistance) dist = solidDistance;
renderer.material.color.a = solidDistance / dist;

create shader and copy and paste then add this to your object

Shader "Kamaly/FarAlpha"
		_MainTex ("Texture", 2D) = "white" {}
		_MinVisDistance("MinDistance",Float) = 0
		_MaxVisDistance("MaxDistance",Float) = 20
			_Color("Color",Color) = (0,0,0,1)
			ZWrite Off
			Blend SrcAlpha OneMinusSrcAlpha
		Tags { "RenderType"="Transparent" }
		LOD 100

			#pragma vertex vert
			#pragma fragment frag 
			// make fog work
			#pragma multi_compile_fog
			#include "UnityCG.cginc"

		struct v2f
		half4 pos       : POSITION;
		fixed4 color : COLOR0;
		half2 uv        : TEXCOORD0;

	sampler2D   _MainTex;
	half        _MinVisDistance;
	half        _MaxVisDistance;

	v2f vert(appdata_full v)
		v2f o;

		o.pos = mul((half4x4)UNITY_MATRIX_MVP, v.vertex);
		o.uv = v.texcoord.xy;
		o.color = v.color;

		half3 viewDirW = _WorldSpaceCameraPos - mul((half4x4)unity_ObjectToWorld, v.vertex);
		half viewDist = length(viewDirW);
		half falloff = saturate((viewDist - _MinVisDistance) / (_MaxVisDistance - _MinVisDistance));
		o.color.a *= (1.0f - falloff);
		return o;

	fixed4 frag(v2f i) : COLOR
		fixed4 color = tex2D(_MainTex, i.uv) * i.color;
	return color;

I think renderer.material.color can only return a new color, and can not just set a new single alpha value.
how about trying this:

renderer.material.color = new Color(renderer.material.color.r,
solidDistance / dist);