int DirectionY = 1; //物体Y轴移动的方向,值是-1跟1
void Update () {
//物体的移动
transform.Translate(new Vector3(0,DirectionY * speed * Time.deltaTime,0));
//判断是不是超出范围,如果是就转方向
if (transform.position.y >= 4) {
DirectionY = -1;
}
if (transform.position.y <= -4) {
DirectionY = 1;
}
}