- Home /
health decrease only once and stop player movement
i am trying to create a script that only triggers -1hp once when I enter the collider before the level restarts using timer but whenever I enter the collider twice before the level restarts I keep losing hp.
I tried using a Boolean and it didn't work. I also tried setting the player movement speed to zero from my movement script so that he/she would stop, that didn't work either.
any help is greatly appreciated. thank you
// this is my code below thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class death : MonoBehaviour
{
public bool one = false;
public static int health1 = 5;
public GameObject player2;
public bool healthchecker;
// Start is called before the first frame update
void Start()
{
player2 = gameObject.transform.parent.gameObject;
healthchecker = true;
}
// Update is called once per frame
void Update()
{
health1 = PlayerPrefs.GetInt("Playerr");
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player" && one == false && healthchecker == true)
{
healthchecker = false;
StartCoroutine(dea());
IEnumerator dea()
{
one = true;
GameControlScript.health -= 1;
yield return new WaitForSeconds(1);
{
SceneManager.LoadScene("level2.1");
}
}
}
else
{
healthchecker = true;
}
}
}
Why do you set healthchecker = true; if you don't want it to be true. I guess you are entering the trigger, set it false, but again enter it somehow and set it true again which will allow the code to run again. How are you moving your player? Is it rigidbody physics or are you using transform.position, therefore it could init some new collider entering.
Answer by kidgoku60 · Dec 14, 2019 at 12:59 PM
Yeah sorry I realized that it keeps the healthchecker true whenever I enter the collider so that Boolean is basically useless....yes I am using rigidbody physics sorry I am new so I am really bad at coding thanks for the reply