Hello,
Im in need of assistance. I came across this code in the unity documentation which turns objects transparent when hit with a raycast, and inserted it into my own game. However im unsure how i would efficiently go back to switching the objects that have been turned transparent back into being solid. Any help would be greatyl appreciated.
Thanks!
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
void Update()
{
RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);
for (int i = 0; i < hits.Length; i++)
{
RaycastHit hit = hits[i];
Renderer rend = hit.transform.GetComponent<Renderer>();
if (rend)
{
// Change the material of all hit colliders
// to use a transparent shader.
rend.material.shader = Shader.Find("Transparent/Diffuse");
Color tempColor = rend.material.color;
tempColor.a = 0.3F;
rend.material.color = tempColor;
}
}
}
}
So are you saying you don’t understand what the alpha channel means and how it’s used in a color? Try changing the value above from 0.3 in the range of 0 (fully transparent) to 1 (fully opaque).
Thank you, but I do understand that part. The part im interested in is changing the objects alpha back to 1 when it isnt being hit by the raycast, because as it is in my game, the player shoots a short ray infront of itself and any walls it hits get turned transparent so the player is still visible behind the wall. But im looking to turn the walls back to being solid again, so an alpha of 1, when it isnt being hit by the raycast.
Thanks.
Without writing the script for you, you’ll need to keep a copy of the renderers you modified last frame so you can reset them this frame, obviously exlcuding the ones you do find. As you find them this frame, you could remove them from last frames results
If you want efficient, then certainly don’t go using a physics query that creates an array of results each frame then just throws them at the garbage collector. For 3D physics your only option to get around that is to use RaycastNonAlloc and reuse an array that’s large enough to contain all the results you’d expect. Also, you’re finding shader details inside a loop that don’t change so you’re repeating the same work over and over again.
Thank you again for another reply, it is much appreciated.
Im very new to unity and programming so im using alot of guides and tutorials to get my way through this process. The information you have told me all makes sense and i understood the theory behind it, im just not experienced enough to put it into practice and code it myself without help.
Would you mind babysitting me through the process please?
Thanks again.