Hello! I need help: I am trying to make an elevator, it moves fine but doesn’t want to stop. I don’t know if the problem is my logic or anything else. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Elevator : MonoBehaviour
{
public int a=0;
public int speed=1;
public void Open()
{
if (this.gameObject.transform.position.y != 1.61)
{
this.gameObject.transform.Translate(Vector3.up * Time.deltaTime * speed);
}
}
public void Close()
{
if (this.gameObject.transform.position.y != -5.34)
{
this.gameObject.transform.Translate(Vector3.down * Time.deltaTime * speed);
}
}
private void Update()
{
if (a % 2 == 1)
{
Open();
}
else if (a % 2 == 0)
{
Close();
}
}
}
It’s because you use inequality operator in your conditions.
Try using inferiority and superiority operators, the condition is always fulfilled because the gameobject y-position wil (almost) never be exactly equal to the value you use.
the thing is that your two values to check if the elevator to stop are too precise (1.61 and -5.34) this means that if the elevator gets at y = -5.35 instead of -5.34 it won’t stop. You can deal with this by instead of using a fixed value, using a range of values at which the elevator should stop:
if(!(transform.position > 1 && transform.position < 2)){
//make it go up
}
also using this.gameObject.transform.Translate
is unnecessary since the code is already about the gameobject Elevator, you can directly use
transform.Translate(. . .);
Hope this helps i just started unity too 
Hi @PinkPowder123 I think it may be because you’re looking for it to stop at a specific value, 1.61 or -5.34. What you could try checking for is whether it’s greater than 1.61 or less than -5.34 like this:
public void Open()
{
if (this.gameObject.transform.position.y >= 1.61)
{
this.gameObject.transform.Translate(Vector3.up * Time.deltaTime * speed);
}
}
public void Close()
{
if (this.gameObject.transform.position.y <= -5.34)
{
this.gameObject.transform.Translate(Vector3.down * Time.deltaTime * speed);
}
}
Often times Unity won’t land on the exact value when you do translations because the floats being changed have many decimals and the value could easily get jumped over by something like 0.001. Let me know if that works.