Question by
ginevra_turco · Apr 14, 2020 at 02:30 PM ·
raycastbugraycasting
raycast bug when hitting two adjacent objects
Hi, i'm trying to change the color of the objects hitted by the raycast and then change the color back when they'e not hitted. I've a bug, when i have two or more gameobjects attcked (so there isn't air between), my raycast doesn't change the color back to the original.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeestRaycast : MonoBehaviour
{
public Transform rayStartPoint;
Color originalColor;
Renderer lastObjRenderer;
void Update()
{
RaycastHit hit;
if (Physics.Raycast(rayStartPoint.position, rayStartPoint.forward, out hit, 100))
{
Debug.DrawRay(rayStartPoint.position, rayStartPoint.forward * hit.distance, Color.green);
Renderer objRenderer = hit.transform.GetComponent<Renderer>();
if (objRenderer != null )
{
if (lastObjRenderer != objRenderer)
{
lastObjRenderer = objRenderer;
originalColor = objRenderer.material.color;
}
objRenderer.material.color = new Color(hit.distance / 10, 1, 1, 1);
}
}
else
{
Debug.DrawRay(rayStartPoint.position, rayStartPoint.forward * 100, Color.red);
if (lastObjRenderer != null)
{
lastObjRenderer.material.color = originalColor;
lastObjRenderer = null;
}
}
}
}
Can you please fix it so the raycast change the color of the renderer even if they are adjacent?
Comment