I’m still a total beginner at this so this might be obvious.
but I’m trying to “highlight” the object I’m looking at from an fps perspective by changing the material.
the object is multiple blocks in an L shape (like the tetris block) all objects are in an empty parent with the rigidbody attached.
so far I managed to change the material of the block that has the same position as the parent.But now I want to have all children to change material aswell. (I want all the blue ones to be yellow if highlighted)
How do I do this? and if possible I would like an explanation to how that solution works so I can understand it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class Highlights : MonoBehaviour
{
public LayerMask Mask;
public Material highlightMaterial;
Material originalMaterial;
GameObject lastHighlightedObject;
void HighlightObject(GameObject gameObject)
{
if (lastHighlightedObject != gameObject)
{
ClearHighlighted();
originalMaterial = gameObject.GetComponentInChildren<MeshRenderer>().sharedMaterial;
gameObject.GetComponentInChildren<MeshRenderer>().sharedMaterial = highlightMaterial;
lastHighlightedObject = gameObject;
}
}
void ClearHighlighted()
{
if (lastHighlightedObject != null)
{
lastHighlightedObject.GetComponentInChildren<MeshRenderer>().sharedMaterial = originalMaterial;
lastHighlightedObject = null;
}
}
void HighlightObjectInCenterOfCam()
{
float rayDistance = 1000.0f;
// Ray from the center of the viewport.
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
RaycastHit rayHit;
if (Physics.Raycast(ray, out rayHit, rayDistance, Mask))
{
GameObject hitObject = rayHit.collider.transform.parent.gameObject;
HighlightObject(hitObject);
}
else
{
ClearHighlighted();
}
}
void Update()
{
HighlightObjectInCenterOfCam();
}
}