Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Need help writing an if statement

Discussion in 'Scripting' started by pryog1, Mar 28, 2020.

  1. pryog1

    pryog1

    Joined:
    Mar 14, 2017
    Posts:
    5
    I am making a game where lava rises and if you touch it you die.

    The lava already has a script where it slowly rises, but because of this, it can't have a collider (it passes through objects).

    My solution was to make a script where if the player's y position was equal to or less that the lava's y position, the scene would reload.

    Unfortunately, I am a complete beginner and I don't know how to go about it.

    I was able to make the two variables to store the positions of the player and the lava, but I don't know how to write the "if" statement to check if the player fell to or below the lava's position.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class death : MonoBehaviour
    6. {
    7.    
    8.     public Transform playerTransform;
    9.     public Transform thisTransform;
    10.    
    11.    
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.        
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.      
    22.     }
    23. }
    24.  
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Hey,
    first of all, why cant you have a collider? The lava changing its position shouldnt matter.

    Anyways, first you calculate the difference in y-position:
    Code (CSharp):
    1. float distanceLavaPlayer = lavaTransform.position.y - playerTransform.position.y
    So now, if the distanceLavaPlayer is above 0, this means the player is below lava.
    Then you want the player to take damage.
    Code (CSharp):
    1. if(distanceLavaPlayer >= 0){
    2.     // make the player take damage
    3. }
    Do the above in Update().

    I would highly recommend learning some basic scripting tho. Will save you more time than you will lose on it. Sebastian Lague did a great series on it on youtube.
     
  3. pryog1

    pryog1

    Joined:
    Mar 14, 2017
    Posts:
    5
    You are a life saver! Thanks for taking the time to help out a beginner. I'll be sure to check out that video series.
     
    Kurt-Dekker likes this.