I have multiple objects in the scene and I’m changing materials for highlighting them. So I’m using this little scrip for Raycast triggering and it’s working well so far.
Sound is playing well on selection too, but I need to trigger the sound only once. Normally I would make a bool comparison, but in this case, it wouldn’t work I guess. because the script is acting on many different objects.
So my attempt is to include a comparison to check if the user is facing another object. But I have no idea how to do that in C#.
Thanks!
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using UnityEditorInternal;
using UnityEngine;
public class SelectionManager : MonoBehaviour
{
[SerializeField] private string selectableTag = "Selectable";
[SerializeField] private Material highlightMaterial;
[SerializeField] private Material defaultMaterial;
private Transform _selection;
private Transform last_selection;
public AudioSource playsound;
private void Update()
{
if (_selection != null)
{
var selectionRenderer = _selection.GetComponent<Renderer>();
selectionRenderer.material = defaultMaterial;
_selection = null;
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
var selection = hit.transform;
if (selection.CompareTag(selectableTag))
{
var SelectionRenderer = selection.GetComponent<Renderer>();
if (SelectionRenderer != null)
{
SelectionRenderer.material = highlightMaterial;
/*
if(GameObject.ReferenceEquals( _selection, last_selection)){
Debug.Log( "equal");
}else{
Debug.Log( "not equal, playing sound");
playsound.Play();
last_selection = _selection;
}
*/
}
}
_selection = selection;
}
}
}