Toggle a bool on only one object at a time by tapping an object.
The goal here is to be able to tap objects and make them transparent, and when they are tapped again, make them solid again.
I have a bunch of gameObjects that I need to toggle a boolean on individually. The bool state changes the current alpha of the material on an object. This function worked great when it was on just one gameObject, but when I applied the scripts to the other objects, the function still changes the bool on all objects at once. I separated the script that had the bool so that it lived on the object.
I am using this script to make a gameObject into a button, then the function below to manipulate the bool in the ObjAlphaBool script.
public class MakeObjectButton : MonoBehaviour
{
public UnityEvent action;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
GameObject obj = hit.collider.gameObject;
obj.GetComponent<MakeObjectButton>().action.Invoke();
}
}
}
public void ToggleAlpha()
{
gameObject.GetComponent<ObjAlphaBool>().ToggleAlphaState();
}
This is the script that should be changing just the current gameObject. But when I use the button on an object, the console prints out the debug for all objects and for both states.
public class ObjAlphaBool : MonoBehaviour
{
public bool AlphaValueBool = true;
public void ToggleAlphaState()
{
AlphaValueBool = !AlphaValueBool;
if (AlphaValueBool == false)
{
newAlpha(gameObject.GetComponent<Renderer>().material, 0.3f);
Debug.Log("Alpha is 0.3");
}
else
{
newAlpha(gameObject.GetComponent<Renderer>().material, 1f);
Debug.Log("Alpha is 1");
}
}
void newAlpha(Material mat, float alphaVal)
{
Color oldColor = mat.color;
Color newColor = new Color(oldColor.r, oldColor.g, oldColor.b, alphaVal);
mat.SetColor("_Color", newColor);
}
}