Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can't seem to get my if statement to work properly?

Discussion in 'Scripting' started by Ginger-Llama, Jun 15, 2019.

  1. Ginger-Llama

    Ginger-Llama

    Joined:
    Jun 15, 2019
    Posts:
    2
    so this is my code:
    upload_2019-6-15_17-1-0.png
    and even when health is equal to above 0, the scene still reloads and I haven't got a clue xD

    Anyone have any ideas?

    EDIT: and I'm following Blackthornprods guide called "HOW TO MAKE A SIMPLE GAME IN UNITY - ENDLESS RUNNER - #2" if that's any help :)
     
  2. Deleted User

    Deleted User

    Guest

    I tested that part of the script and the scene reloaded only once. Are you sure Health is set to 3 in the Inspector?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class Test : MonoBehaviour
    7. {
    8.     public int health = 3;
    9.  
    10.     private void Update()
    11.     {
    12.         if (health <= 0)
    13.         {
    14.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    15.  
    16.             Debug.Log("Scene reloaded");
    17.         }
    18.     }
    19. }
     
  3. Ginger-Llama

    Ginger-Llama

    Joined:
    Jun 15, 2019
    Posts:
    2
    Hmm that's weird I'm pretty sure it's set to 3 in the inspector
     
  4. EdGunther

    EdGunther

    Joined:
    Jun 25, 2018
    Posts:
    183
    Hi I'm Ed and I'm bad at coding

    Check this talk about Variables in Scriptable Objects


    I would make your player HP an intVariable (like the floatVariable described, but an int)

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.SceneManagement;
    4.  
    5. //This script handles the code for player death
    6. public class OnDeathScript: MonoBehaviour
    7. {
    8.     public intVariable playerHealth;  // ----- drag playerHealth scribltable object in inspector-----
    9.  
    10.     void Update()
    11.     {
    12.         Debug.Log(health.value); // ----- real-time display of HP -----
    13.  
    14.         if (health.value <= 0)
    15.         {
    16.             Debug.Log("Player Died")
    17.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    18.         }
    19.     }
    20. }
    21.