i made some script when there is some Obstacle between Camera and Player, the material of that obstacle will transparent. the problem here, idk how to make it back to normal after that obstacle already not between Camera and Player. i already try looking at Google or Youtube, but cant find the right asnwer
public static int SizeID = Shader.PropertyToID("_Size");
Material obstacle;
GameObject player;
private void Start() {
player = GameObject.Find("Player");
}
private void Update()
{
var dir = player.transform.position - transform.position;
var ray = new Ray(transform.position, dir.normalized);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject != player)
{
obstacle = hit.collider.gameObject.GetComponent<Renderer>().material;
obstacle.SetFloat(SizeID, 0.7f);
}
else
{
obstacle.SetFloat(SizeID, 0f);
}
}
}
The general pattern is to break it up into two parts:
a script that looks for obstacles (ALL obstacles) that are between the player and target and informs them to be transparent
a script that controls the transparency of any single one object, generally by receiving calls from the first script above.
If you insist on going with one script (such as above) then you need to track all the objects each frame of the raycast so that when you are no longer hitting them, you can restore them.
It’s a bit strange that you have a raycast for just one hit, what if there are several objects between the player and the camera? So, it might be better to use RaycastAll.
The logic is simple: you need to store the objects hit by the ray in an array (list, hash list, dictionary, whatever is convenient for you). If there are objects in this array that the ray didn’t hit in the current frame, these are objects from the previous raycast, and you need to restore their transparency and remove them from the array. So, you should always have a list of previous objects that the ray hit in the last frame and a list of objects in the current frame. Objects that are not in the current frame (in the raycast array) are the ones to be restored.
And if you only have one object that can be between the player and the camera, then instead of an array, use a field to store the object hit by the ray. After the raycast, check if the previous object (stored in the field) is not the current one (the one just hit by the ray). If it’s not, restore the transparency of the previous object and store the new object hit by the ray in this field for the current frame. I think you get the idea.