[英]C# how do I get data from the class that I used the method in another class without using a parameter
I have a static Player class that I have a Jump method in it. 我有一个静态Player类,其中有一个Jump方法。 It takes a Rigidbody2D parameter so I have to call it by typing
它需要一个Rigidbody2D参数,所以我必须通过键入来调用它
Player.Jump(GetComponent<Rigidbody2D>);
but I want to get the Rigidbody2D component in the Jump method and call it by typing 但我想在Jump方法中获取Rigidbody2D组件,并通过键入以下内容进行调用
Player.Jump();
Is there any way to do this? 有什么办法吗? Can I get the Rigidbody2D component from the Jump method?
我可以从Jump方法获取Rigidbody2D组件吗?
My Jump code: 我的跳转代码:
/// <summary>
/// Makes the given Rigidbody2D jump.
/// </summary>
public static void Jump(Rigidbody2D rb)
{
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.AddForce(new Vector2(0, JumpHeight));
}
Class that I'm using the Jump method 我正在使用Jump方法的类
if (Player.CanMove)
{
Player.Move(rb);
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
if (tempMaxJumps > 0)
{
Player.Jump(rb);
tempMaxJumps--;
}
else
{
canJump = false;
}
}
}
If you really need the player class to stay a static class, i suggest simply adding a 如果您真的需要播放器类来保持静态类,我建议您只需添加一个
public static RigidBody2D Rigidbody;
to which you can assign to once in the Start
of the class calling Jump
您可以在调用
Jump
的类的Start
将其分配给该对象一次
However this whole question seems like bad practice, a Player
script should generally be inherit from MonoBehaviour
and be attached to the player GameObject in your scene. 但是,整个问题似乎是不明智的做法,
Player
脚本通常应继承自MonoBehaviour
,并附加到场景中的玩家GameObject。 Then inside this Player
script you can check for input and have a Jump-method 然后,在此
Player
脚本中,您可以检查输入并具有跳转方法
You could create a static member which would have a reference to the rigidbody and set the reference at some point prior to calling Jump, but that's a bad idea. 您可以创建一个静态成员,该成员将具有对刚体的引用,并在调用Jump之前的某个时刻设置引用,但这是一个坏主意。
By using the static class to make the player object jump, you are breaking abstraction. 通过使用静态类使播放器对象跳转,您正在破坏抽象。 Now you have code outside of your player object that is influencing the player, leading to code spaghetti.
现在,您的代码超出了影响播放器的播放器对象,从而导致了意大利面条。
Like this? 像这样?
public static class Player
{
public static Rigidbody2D Jump()
{
return new Rigidbody2D();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.