Home > front end >  Unity 2D - how to check if my gameobject/sprite is below ceratin Y lvl?
Unity 2D - how to check if my gameobject/sprite is below ceratin Y lvl?

Time:10-13

I've been trying to get a script working to check if my player is below a certain Y lvl, for a platformer. so it can be respawned to the beginning, But how do I put the y lvl inside a variable to check it? i cant figure it out lol

CodePudding user response:

I am assuming you want to just want to compare (==, <=, >=, all that jazz is what I mean by comparing just in case you were not aware) the Y value to something like 10 for example. This is easy and you don't even need a variable necessarily for this.

//For the object position relative to the world
if(transform.position.y == 10) //"transform" gives you acces to the transform component 
{                              //of the object the script is attached to
    Debug.Log("MILK GANG");
}

//For the object position relative to its Parent Object
if(transform.localPosition.y == 10)
{
    Debug.Log("MILK GANG");
}

If you want to change the value of the position of your object then

transform.position = new Vector2(6, 9)//Nice
                                      //BTW new Vector2 can be used if you dont
                                      //want to assign a completely new variable

However, if you want to get a reference (Basically a variable that tells the code your talking about this component) to it.

private Transform Trans;

void Awake() //Awake is called/being executed before the first frame so its
{            //better than void Start in this case
    Trans = GetComponent<Transform>();

    Trans.position = new Vector2(69, 420); //Nice
}                                          

This is the code way of doing it but there's another way that uses Unity

[SerializeField] private Transform Trans; 

//[SerializeField] makes the variable changeable in Unity even if it is private so you
//can just drag and drop on to this and you good to go 

Hope this help if it doesn't then welp I tried lel

CodePudding user response:

In the Update() run something like:

if(player.transform.position.y < 1)
 {
           //do something
 }

where 'player' is the GameObject in question.

CodePudding user response:

You can use a script added to gameobject to check transform.position of the object.

if(transform.position.y < ylvl)
{
//do something
}

where ylvl is the integer of the height you want to check

  • Related