- Home /
Question by
Th1nk3r · Jul 04, 2020 at 10:48 AM ·
prefabraycastingfirst-personprefab changing at runtimehighlighting
Highlighting prefabs with different colors when a first person player looks at them,Highlighting objects programatically with different materials when the first person player looks at them
I want to highlight the objects with the selectable tag when the player looks at them. There are two types, they are either red or blue. I want to highlight them with a lighter shade of their default material. I have the following code, but it doesn't work:
public class SelectionManager : MonoBehaviour
{
[SerializeField] Material highlightedRed;
[SerializeField] Material highlightedBlue;
[SerializeField] string selectableTag = "Selectable";
[SerializeField] Material defaultRed;
[SerializeField] Material defaultBlue;
[SerializeField] GameObject redBocce;
[SerializeField] GameObject blueBocce;
private Transform _selection;
void Start()
{
var blueRenderer = blueBocce.GetComponent<MeshRenderer>();
var redRenderer = redBocce.GetComponent<MeshRenderer>();
redRenderer.material = defaultRed;
blueRenderer.material = defaultBlue;
Update();
}
void Update()
{
if(_selection != null){
var selectionRenderer = _selection.GetComponent<MeshRenderer>();
if(selectionRenderer.material == highlightedBlue){
selectionRenderer.material = defaultBlue;
}
else if(selectionRenderer.material == highlightedRed){
selectionRenderer.material = defaultRed;
}
_selection = null;
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
var selection = hit.transform;
if(selection.CompareTag(selectableTag)){
var selectionRenderer = selection.GetComponent<MeshRenderer>();
if(selectionRenderer != null && selectionRenderer.material == defaultRed){
selectionRenderer.material = highlightedRed;
}
else if(selectionRenderer != null && selectionRenderer.material == defaultBlue){
selectionRenderer.material = highlightedBlue;
}
_selection = selection;
}
}
}
}
Comment