user8524747
user8524747

Reputation:

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. It takes a Rigidbody2D parameter so I have to call it by typing

Player.Jump(GetComponent<Rigidbody2D>);

but I want to get the Rigidbody2D component in the Jump method and call it by typing

Player.Jump();

Is there any way to do this? Can I get the Rigidbody2D component from the Jump method?

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

if (Player.CanMove)
    {
        Player.Move(rb);

        if (Input.GetKeyDown(KeyCode.Space) && canJump)
        {
            if (tempMaxJumps > 0)
            {
                Player.Jump(rb);
                tempMaxJumps--;
            }
            else
            {
                canJump = false;
            }
        }
    }

Upvotes: 0

Views: 170

Answers (3)

Fix
Fix

Reputation: 198

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.

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.

Upvotes: 3

Fredrik Widerberg
Fredrik Widerberg

Reputation: 3108

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

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. Then inside this Player script you can check for input and have a Jump-method

Upvotes: 3

J. Doe
J. Doe

Reputation: 31

Like this?

public static class Player
{
    public static Rigidbody2D Jump()
    {
        return new Rigidbody2D();
    }
}

Upvotes: 0

Related Questions