This script is inside a prefab called block. All I’m trying to do is make my slider control a block’s height. There are 2 blocks. When I click on a block it’s supposed to change it’s color to red and the slider’s value changes to the block’s height. This is done successfully. But when I click on another block and click again on the initial block the slider’s height changes to the previous block’s height and the current block matches the previously clicked block’s height. I suspect the problem is in my Update function. Also if it helps, I can make more blocks during runtime that’s why I have to delegate the AdjustHeight function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Block_Change_Behavior : MonoBehaviour {
private GameObject CurrentButtonHolder;
private GameObject tagBearer;
public GameObject slider;
public float height = 1f;
void Start () {
slider = GameObject.FindWithTag ("Block_Height_Slider");
}
void OnMouseDown() {
CurrentButtonHolder = GameObject.FindWithTag("Current_Button_Holder");
if (CurrentButtonHolder.GetComponent<Current_Button_Variable_Script> ().currentButtonSelected == "Change") {
if (GetComponent<Renderer> ().material.color == Color.red) {
GetComponent<Renderer> ().material.color = Color.green;
}
else if (GetComponent<Renderer>().material.color == Color.green) {
GetComponent<Renderer> ().material.color = Color.red;
slider.GetComponent<Slider> ().value = transform.localScale.x; // this only works the first time
if (tagBearer == null) {
tagBearer = GameObject.FindWithTag ("selected");
if (tagBearer != null && tagBearer != this.gameObject) {
//Debug.Log ("found tag bearer");
tagBearer.transform.gameObject.tag = "not_selected";
tagBearer.GetComponent<Renderer> ().material.color = Color.green;
}
tagBearer = null;
}
transform.gameObject.tag = "selected";
}
}
else if (CurrentButtonHolder.GetComponent<Current_Button_Variable_Script> ().currentButtonSelected == "Delete") {
//Delete itself
Object.Destroy(this.gameObject);
}
}
void Update () {
//I suspect this is causing problems.
if (transform.gameObject.tag == "selected") {
slider.GetComponent<Slider> ().onValueChanged.AddListener (delegate {AdjustHeight (slider.GetComponent<Slider> ().value);});
transform.localScale = new Vector3 (4, height, 4);
transform.localRotation = Quaternion.Euler (0, 0, 0);
}
}
public void AdjustHeight (float newHeight) {
height = newHeight;
// Debug.Log(newHeight);
}
}