Reputation: 105
Trying to decrease value of float - timeBtwSpan, when value of LevelValue go up.
so at the moment when LevelValue change to 2 I trigger my if statment to decrease TimebtwSpan, and it is happening but value continue to decreasing infinity,
shouldn't this decrease it once ?
as per function when LevelValue == 2 something should happen.. but why it is continue to happening?
public class SPawnHorizontal : MonoBehaviour
{
public GameObject enemy1;
Vector2 whereToSpawn;
public float timeBtwSpan;
public float decreaseSpawnTime;
public float minTime = 0.5f;
private Vector2 screenBounds;
void Start()
{
screenBounds = Camera.main.ScreenToViewportPoint(
new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
StartCoroutine(decrease());
}
public void Update()
{
if (TimeLevel.levelValue == 2)
{
timeBtwSpan -= decreaseSpawnTime;
}
}
private void spawning()
{
GameObject a1 = Instantiate(enemy1) as GameObject;
a1.transform.position = new Vector2(screenBounds.x * -20,
Random.Range(-20, 20));
}
IEnumerator decrease()
{
while (true)
{
yield return new WaitForSeconds(timeBtwSpan);
spawning();
}
}
}
Upvotes: 2
Views: 151
Reputation: 925
It continues to decrease because Update()
fires on every frame. In your case you can use a toggle:
var _onetime = false;
public void Update()
{
if (!_onetime && TimeLevel.levelValue == 2)
{
timeBtwSpan -= decreaseSpawnTime;
_onetime = true;
}
}
// edit:
To incorporate multiple level changes, you have to keep track of your previous level value and register a change in value. This would look something like the following (assuming you want to start decreasing at levelValue >= 2
:
var _previousLevel = -1;
public void Update()
{
// added a minimum levelValue of 2 for the trigger
if(_previousLevel != TimeLevel.levelValue && TimeLevel.levelValue >= 2)
{
timeBtwSpan -= decreaseSpawnTime;
_previousLevel = TimeLevel.levelValue;
}
}
Upvotes: 4
Reputation: 71
You can just write your decreaseSpawnTime() instead of putting it in update(), and It would work since the function update() is being executed infinitely and your levelvalue will always be 2 unless your game reaches another level.
public void decreaseSpawnTime()
{
if (TimeLevel.levelValue == 2)
{
timeBtwSpan -= decreaseSpawnTime;
}
}
public void update()
{
}
Or
The other workaround that I've come up with is this.
private boolean decreased;
public function update()
{
if(!decreased)
{
if (TimeLevel.levelValue == 2)
{
timeBtwSpan -= decreaseSpawnTime;
decreased = 1;
}
}
}
Upvotes: 2