- Home /
Can you save variables one second ago and then use it to make an "if" statement?
I am trying to make a game where the way you die is by standing still on the z coordinate. I need help to a make a code to when the position of the character is equal to the position of the character one second ago, the game ends. I tried using
private rb.position.z prev;
WaitForSeconds(1)
if (prev = rb.position.z){
...
}
But clearly doesn't work. I need help!
Answer by Rygaran · Jun 09, 2018 at 08:55 PM
WaitForSeconds is use in coroutines so you could look for tutorials about them. A simple way of doing this is in the update function
float lastZ;
float counter = 0;
void Start()
{
lastZ = transform.position.z;
}
void Update()
{
if(lastZ == transform.position.z){
counter += Time.deltaTime;
}
else
{
counter = 0;
}
if(counter >= 1){
Die();
}
lastZ = transform.position.z;
}
Answer by fluxhackspro · Jun 09, 2018 at 08:53 PM
Well dont really understand what you're trying to go for but i belive you can use PlayerPrefs to save the variable. Then access it again and use it in the ifstatement. Though this cant be done every frame as it would be very heavy for the game.
Answer by SlowCircuit · Jun 09, 2018 at 11:26 PM
In Start(), call StartCoroutine(KeepThemMoving()) and put this somewhere in the script:
IEnumerator KeepThemMoving() {
Vector3 pos = transform.position;
while (true) {
yield return new WaitForSeconds(1);
if (pos.z == transform.position.z) { Death(); }
pos = transform.position;
}
}
You will have to make the Die() function of course and if the position you're getting isn't on the script's object then you'll need to use the target transform.