RaycastAll Method Returns Only One Object

I am making a 3D isometric game with Unity. This is my code for Raycasting:

using UnityEngine;

public class Raycasting : MonoBehaviour
{
    public Transform player;
    public LayerMask obstacleLayer; // If you wanna control the objects in one layer

    public float fadeSpeed = 3f;
    private Material objMaterial;
    private Color originalColor;

    private Color tempColor;



    void Update()
    {
        Vector3 direction = player.position - transform.position;

        float distance = direction.magnitude;
        direction.Normalize();

        // All objects in that direction:
        RaycastHit[] hits = Physics.RaycastAll(transform.position, direction, distance, obstacleLayer);

        foreach (RaycastHit hit in hits)
        {
            Debug.Log("Arada kalan obje: " + hit.transform.name);

            objMaterial = hit.transform.GetComponent<Renderer>().material;

            tempColor = objMaterial.color;
            tempColor.a = Mathf.Lerp(tempColor.a, 0f, Time.deltaTime * fadeSpeed);
            objMaterial.color = tempColor;
        }
    }
}

This script is for hiding the objects between player and camera, so users can see their players.

However only the first object is assigned to the hits array. So, only one object becomes transparent.


As you an see, my character is behind 2 walls but only one of them gets masked. hits array has one element.

What can I do to assign all objects between player and camera to hits array?

But there’s always one of the red blocks that becomes transparent when the player moves?

What’s the transform of “Raycasting”? Is this on the Camera object?

You should use Gizmos.DrawRay to visualize your ray to check that this is correct (gizmos are visible only in scene view).

1 Like

The raycast call is correct, and it will return all the colliders that it finds in the array. If it’s only returning 1 then it really is only hitting 1 collider, and there must be something wrong somewhere elese.

1 Like

Gizmos.DrawRay helped a lot to understand the problem!

This is how it looks. As you can see, the camera is too close to the character. So, raycast doesn’t touch to the other objects. However, in game screen the camera seems very far away. I don’t know why it is far away but at least I know the problem now. Thanks.