Hi guys,
I’ve been pondering over this for way too long. Basically what I’m trying to achieve is to highlight an object when the crosshair detects an object. This is a 3D game, with a crosshair in the middle. If the player walks up to the object within range, the crosshair turn red indicating something can be done with the object. This works perfectly, but now I’d like to actually highlight the object by getting the original material attached to the gameobject and just change its color.
All the tutorials I’ve come across let you assign a totally different material on raycast, not something I want to do, just get the original color on the material, change it once the raycast detects it and restore the original material (without the color change) when the ray no longer detects the object.
This is what I have so far that works:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class Highlights : MonoBehaviour {
public Material highlightMaterial;
Material originalMaterial;
GameObject lastHighlightedObject;
void Update()
{
HighlightObjectInCenterOfCam();
}
void HighlightObject(GameObject gameObject)
{
if (lastHighlightedObject != gameObject)
{
ClearHighlighted();
originalMaterial = gameObject.GetComponent<MeshRenderer>().sharedMaterial;
gameObject.GetComponent<MeshRenderer>().sharedMaterial = highlightMaterial;
lastHighlightedObject = gameObject;
}
}
void ClearHighlighted()
{
if (lastHighlightedObject != null)
{
lastHighlightedObject.GetComponent<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;
// Check if we hit something.
if (Physics.Raycast(ray, out rayHit, rayDistance))
{
// Get the object that was hit.
GameObject hitObject = rayHit.collider.gameObject;
HighlightObject(hitObject);
} else
{
ClearHighlighted();
}
}
}
As you can see, it assigs a totally different material once it hovers over the detected gameobject, this just needs to be replaced by the orginal material + a color change. But I have no clue how to do that?
I assume the public Material highlightMaterial needs to be removed, and something needs to happen inside the HighlightObject function.
Any help would be greatly appreciated!