- Home /
Make a code line execute only once
I've written a stagger script that makes the enemy not move for a bit after getting knocked back. Unfortunately, it keeps on setting the variable that sets whether or not an object is knocked back (for movements) to false. This is because when the Stagger timer is set to 0 when not used, but when its done (aka set to 0) it sets the knocked back variable to false. Is there a way that I can make a system that only checks that code line once or perhaps something that checks if the KnockedBack variable was set to true a bit ago?
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StaggerPlayer : MonoBehaviour {
public bool KnockedBack;
public float StaggerTime;
public float StaggerTimer;
void Update() {
if(this.gameObject.GetComponent<Rigidbody2D>().velocity == new Vector2(0, 0) && this.gameObject.GetComponent<EnemyMovement>().KnockedBack == true && StaggerTime == 0) {
StaggerTime = StaggerTimer;
}
if(StaggerTime > 0) {
StaggerTime -= Time.deltaTime;
}
if(StaggerTime < 0) {
StaggerTime = 0;
}
if(StaggerTime == 0) {
this.gameObject.GetComponent<EnemyMovement>().KnockedBack = false;
}
}
}
Answer by Captain_Pineapple · Apr 14, 2018 at 01:08 PM
Not sure if i got your problem right but try the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StaggerPlayer : MonoBehaviour {
public bool KnockedBack;
public float StaggerTime;
public float StaggerTimer;
private bool doKnockBackOnce;
void Update() {
if(this.gameObject.GetComponent<Rigidbody2D>().velocity == new Vector2(0, 0) && this.gameObject.GetComponent<EnemyMovement>().KnockedBack == true && StaggerTime == 0) {
StaggerTime = StaggerTimer;
doKnockBackOnce = true;
}
if(StaggerTime > 0) {
StaggerTime -= Time.deltaTime;
}
if(StaggerTime < 0) {
StaggerTime = 0;
}
if(StaggerTime == 0 && doKnockBackOnce == true) {
doKnockBackOnce = false;
this.gameObject.GetComponent<EnemyMovement>().KnockedBack = false;
}
}
}
Answer by argentummanusbeta · Apr 14, 2018 at 01:11 PM
I don't know 100% what you are trying to ask, but here is my best answer: Maybe try using a collider on the enemy object and the void OnCollisionEnter to sense if an object has collided with it, then it initiates a timer that makes the enemy stagger.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
IF Statement Being Ignored 3 Answers
Change size of an object up to a limit 2 Answers
How to make object instantiate once but still call next function. 1 Answer