I understand you know how to get the distance to an object and pass a variable to it. Specifically blending the material alpha channel is done in the shader. All you need to do is take a default shader, add a slider “opacity” or whatever, then multiply the alpha with that before outputting it. Then you can just reference the material in code and modify the slider to change opacity. A similar technique is used for blending two textures together, I use it for Day/Night skyboxes, and for that I do indeed use mathf.lerp to get a smooth transition. The wiki has a “blend 2 textures” shader as an example. Here’s an UAnswers topic with what you seem to be looking for as first answer.
using UnityEngine;
public class FadeScript : MonoBehaviour
{
[SerializeField] private GameObject _sphere;
[SerializeField] private GameObject _cube;
private float _myProximity = 5;
void Update ()
{
float absoluteDistance = Mathf.Abs(Vector3.Distance(_cube.transform.position, _sphere.transform.position));
if (absoluteDistance > _myProximity)
_sphere.renderer.material.color = new Color(1, 1, 1, 0);
else if (absoluteDistance < _myProximity absoluteDistance > 0)
{
float alpha = 1 / absoluteDistance / _myProximity; // Get the inverse as it gets closer
_sphere.renderer.material.color = new Color(1, 1, 1, alpha);
}
else
_sphere.renderer.material.color = new Color(1, 1, 1, 1);
Vector3 _cubePos = _cube.transform.position;
_cube.transform.position = new Vector3(_cubePos.x + Input.GetAxis("Horizontal"), _cubePos.y, _cubePos.z);
}
}
Just assign a cube and a sphere to the script at design time, then make sure you set the sphere’s material to be transparent (i.e a material with an alpha channel.)
As you move the left and right arrow keys, you will see it fade in/out and blank out when proximity has been exceeded.