- Home /
Question by
Tubestorm · Nov 28, 2020 at 01:18 AM ·
unity 5gameobject3draycastingselecting objects
Selecting and deselecting gameobject to change material
Hello,
I am having some issues with my code. I am trying to create a highlighting feature so a player can click on a game object and see what they have selected.
I would like it to stay highlighted till they select another object.
when they select another object the default material would be applied back to the previous gameobject. and it would continue for each object them select and deselect.
can anyone help me. I've tried a few things but it just keeps the color the same.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelectionManager : MonoBehaviour
{
[SerializeField] private string selectableTag = "Selectable";
[SerializeField] private Material highlightMaterial;
private Material originalMaterial;
private GameObject selected;
private GameObject oldSelected;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Renderer selectionRenderer;
//change the color to the highlight
if (Input.GetMouseButtonDown(0))
{
//if selected set to highlight color
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 300.0f))
{
selected = hit.transform.gameObject;
Debug.Log("1111 new Selection --> " + selected);
if (selected.CompareTag(selectableTag))
{
if(selected != oldSelected || oldSelected == null)
{
//save the original material
selectionRenderer = selected.GetComponent<Renderer>();
originalMaterial = selectionRenderer.material;
selectionRenderer.material = highlightMaterial;
Debug.Log("Old Selection --> " + oldSelected);
Debug.Log("new Selection --> " + selected);
}
else
{
oldSelected = selected;
Debug.Log("you have selected a new building");
oldSelected.GetComponent<Renderer>().sharedMaterial = originalMaterial;
}
//comment 2
}
}
//comment 3
}
//comment1
}
void ClearSelection()
{
if (selected == null)
{
return;
}
else
{
selected.GetComponent<Renderer>().sharedMaterial = originalMaterial;
selected = null;
}
}
}
Comment
Edit: Oh I see you want to maintain the selection state. Let me rewrite that.