有没有办法将这个 Unity 2d 代码分解成单独的方法

Is there a way to break this Unity 2d code into seperate methods

我正在尝试使用屏幕上的按钮上下梯子当前代码使用 W 和 S 键工作得很好,但我不太确定如何将代码放入单独的方法中以便触摸可以访问它。

我正在研究从单独的脚本访问播放器和梯子上的碰撞器,但他们说无法完成。我还尝试将 Keycode 分配给一个方法内的单独变量,然后将此方法分配给屏幕上的键,但这没有用。

public void OnTriggerStay2D(Collider2D other)
{
    if (other.tag == "Player" && Input.GetKey(KeyCode.W))
    {
        other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, speed);
    }
    else if (other.tag == "Player" && Input.GetKey(KeyCode.S))
    {
        other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -speed);
    }
    else{
        other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 1);
    }
}

你的问题有点含糊。它可能有助于提供更详细的场景。但是,将其重构为一种方法以便其他东西可以访问它似乎并不复杂,除非我误解了你。

public void OnTriggerStay2D(Collider2D other)
{
    RigidBody2D rigidBody2d =  other.GetComponent<Rigidbody2D>();

    if (other.tag == "Player" && Input.GetKey(KeyCode.W))
    {
        SetVelocity(rigidBody2d, 0, speed);
    }
    else if (other.tag == "Player" && Input.GetKey(KeyCode.S))
    {
        SetVelocity(rigidBody2d, 0, -speed);
    }
    else
    {
        SetVelocity(rigidBody2d, 0, 1f);
    }
}

// public, assuming you want to access this from somewhere else. 
public void SetVelocity(Rigidbody2D rigidBody, float horizontalSpeed, float verticalSpeed)
{
    rigidBody.velocity = new Vector2(horizontalSpeed, verticalSpeed);
}

没有足够的细节来解决问题,但是,除非我完全误解了你,否则如果你只想使用屏幕触摸输入而不是键盘输入来移动播放器,那么最简单的处理方法就是不要改变太多在您的工作代码中,只需将布尔变量分配给输入条件并检查它们,而不是在您共享的函数内检查键盘输入。

因此,例如,函数看起来像:

    public void OnTriggerStay2D(Collider2D other)
    {
        if (other.tag == "Player" && UpKeyPressed)
        {
            other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, speed);
        }
        else if (other.tag == "Player" && DownKeyPressed)
        {
            other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -speed);
        }
        else{
            other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 1);
        }
    }

其中 UpKeyPressed 和 DownKeyPressed 是布尔变量,当您触摸基于屏幕的按键或基于触摸的输入的 UI 时,可以将其设置为 true/false。