See through wall feature

Hi All! I’m following the unity course about making an rpg game, and I’m wondering if there’s an easy way of setting up the player to be always visible when he is behind something like a tree or a house

Hi! Welcome to the community.

The easiest way to solve this is with shaders, if you don’t know how to code shaders then use RaycastAll, and curiously enough, Unity actually has an example of what you want to do, you’ll just have to modify the code to your needs.

thanks!

Here’s my quick and dirty solution to hiding buildings and trees that get in the way of the camera (Note: This outright hides the building, not making it transparent, so requires no shader work)

First, I created a class

using System.Collections.Generic;
using UnityEngine;

public class HideableObject : MonoBehaviour
{
    private List<Renderer> renderers = new List<Renderer>();

    private void Awake()
    {
        foreach (Renderer rend in GetComponentsInChildren<Renderer>())
        {
            renderers.Add(rend);
        }
    }

    public void SetVisibility(bool visible = true)
    {
        foreach (Renderer rend in renderers)
        {
            rend.enabled = visible;
        }
    }
}

I put this on any object that I want disappeared when it is blocking the player. This object must have a collider to work.

Then I add this to PlayerController:

        void HideBlockingObjects()
        {
            var cameraTransform = Camera.main.transform;
            Ray ray = new Ray(cameraTransform.position, transform.position - cameraTransform.position);
            var hits = Physics.RaycastAll(ray, Vector3.Distance(transform.position, cameraTransform.position));
            List<HideableObject> newHideableObjects = new List<HideableObject>();
            foreach (var hit in hits)
            {
                if (hit.transform.TryGetComponent(out HideableObject hideableObject))
                {
                    hideableObject.SetVisibility(false);
                    hiddenObjects.Remove(hideableObject);
                    newHideableObjects.Add(hideableObject);
                }
            }
            foreach (HideableObject hideableObject in hiddenObjects)
            {
                hideableObject.SetVisibility(true);
            }
            hiddenObjects = newHideableObjects;
        }

Finally, call HideBlockingObjects as the first line in Update.

1 Like

Hi Brian, thanks! I also found a really easy way of doing this using URP’s render passes, here’s a link for future reference in case someone will search for it

Privacy & Terms