How to get only one object to select at a time (in game)?
So I have several blocks , with a script attached that changes between two materials when clicked on. The challenge I'm having is getting only one block to change materials at a time, so that when I select another block, any previously selected will deselect. I'm just using an array to cycle through the two materials.
[CODE] using UnityEngine;
public class ColorEnChange : MonoBehaviour {
public Material[] material;
Renderer rend;
public int index = 0;
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = material[0];
}
private void OnMouseDown()
{
if (material.Length == 0)
{
return;
}
if (Input.GetMouseButton(0))
{
index += 1;
if (index == material.Length + 1)
{
index = 1;
}
rend.sharedMaterial = material[index - 1];
}
}
}
[/CODE]
Picture: Too many blocks selected. Want blocks that are selected to deselect when another clicked on (in game).
You can add a delegate event for each block. When a block click all it have to do is make an event to tell other block to deactivate.
What would the basic structure of that code look like? I'm really new to this, so it's difficult to understand at the moment.
http://www.unitygeek.com/delegates-events-unity/
void OnClickObject()
{
//DisableEvent.Invoke(); // Call to every button
//do whatevermethod here
// DisableEvent.Subscribe( this button );
}
Answer by DawdleDev · Sep 03, 2018 at 08:31 PM
Try using a singleton. It keeps track of the last selected renderer, and deselects it every time you select a new renderer.
.
using UnityEngine;
public class ColorEnChange : MonoBehaviour {
public Material[] material;
public static Renderer Selection;
Renderer rend;
public int index = 0;
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = material[0];
}
private void OnMouseDown()
{
if (material.Length == 0)
{
return;
}
if (Input.GetMouseButton(0))
{
index += 1;
if (index == material.Length + 1)
{
index = 1;
}
rend.sharedMaterial = material[index - 1];
if (Selection) {
Selection.rend.sharedMaterial = whatever material deselected is;
}
Selection = rend;
}
}
}