Solved! As @Athanasios Kataras suggested, making the variable persist solved the problem. I had actually tried to make it persist before, but it did not work. I only now remembered that I did not actually save the file.
Here is the reworked code:
public float height = 10f;
public float width = 2f;
public float defaultSpread = 10f;
public Color color = Color.grey;
public bool resizeable = false;
public float resizedSpread = 20f;
public float resizeSpeed = 3f;
[SerializeField]
float velocityMin = 210;
float spread = 0;
bool resizing = false;
CharacterController player;
Texture2D texture;
void Awake()
{
//set spread
spread = defaultSpread;
player = GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterController>();
texture = new Texture2D(1, 1);
texture.SetPixel(0, 0, color);
texture.wrapMode = TextureWrapMode.Repeat;
texture.Apply();
}
void Update()
{
if (player.velocity.sqrMagnitude > velocityMin) { resizing = true; } else { resizing = false; }
if (resizeable)
{
if (resizing)
{
//increase spread
spread = Mathf.Lerp(spread, resizedSpread, resizeSpeed * Time.deltaTime);
}
else
{
//decrease spread
spread = Mathf.Lerp(spread, defaultSpread, resizeSpeed * Time.deltaTime);
}
//clamp spread
spread = Mathf.Clamp(spread, defaultSpread, resizedSpread);
}
}
void OnGUI()
{
//up rect
GUI.DrawTexture(new Rect(Screen.width / 2 - width / 2, (Screen.height / 2 - height / 2) + spread / 2, width, height), texture);
//down rect
GUI.DrawTexture(new Rect(Screen.width / 2 - width / 2, (Screen.height / 2 - height / 2) - spread / 2, width, height), texture);
//left rect
GUI.DrawTexture(new Rect((Screen.width / 2 - height / 2) + spread / 2, Screen.height / 2 - width / 2, height, width), texture);
//right rect
GUI.DrawTexture(new Rect((Screen.width / 2 - height / 2) - spread / 2, Screen.height / 2 - width / 2, height, width), texture);
}
It is still running in OnGUI because I am using GUI functions, and also because I get 400 fps when this game is running, I really don’t need to spend the time to edge out a tiny bit of performance.
CLICK HERE to find out more related problems solutions.