my C# isnt working

using UnityEngine;
using System.Collections;

public class PlayerScripts : MonoBehaviour
{

public float jumpPower = 10.00f;
public bool isGrounded = false;
Rigidbody2D myRigidbody;
// Use this for initialization
void Start()
{
myRigidbody = transform.GetComponent();
}

void FixedUpdate()
{
if (Input.GetKey(KeyCode.Space)&& isGrounded)
{
myRigidbody.AddForce(Vector3.up * (jumpPower * myRigidbody.mass * myRigidbody.gravityScale * 20.0f));
}
}

void onCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == “Floor”)
{
isGrounded = true;
}
}
void onCollisionStay2D(Collision2D other)
{
if (other.gameObject.tag == “Floor”)
{
isGrounded = true;
}
}
void onCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag == “Floor”)
{
isGrounded = false;
}
}
}

Hi there,

I’m no moderator, but it makes it easier to get answer if:

EDIT:
And in general, you are not paying anyone for some service, saying just “help, not working” and printing code on screen might not be the best approach to get help :slight_smile:

So, what is not working?

Do you get some error message?

Do you have an image of your problem?

1 Like

The log is very likely showing you that this doesn’t make sense:

myRigidbody = transform.GetComponent();

You don’t attach Rigidbodies to Transforms.

You can call GetComponent on any Component. Transform is a Component, so this would work.

It’s just silly, of course, because your script is also a component, so you can just call GetComponent directly.

I agree with @eses here… if you (the OP) want help, you should maybe ask an actual question (and include some details).

I didn’t say he couldn’t do it.
I am saying his log will very likely say that the rigidbody is null because attaching a rigidbody to a transform is weird.

No, it’s really not. I don’t think you understand what GetComponent does. It looks for another component on the same GameObject as the component you’re calling it on.

If your GameObject has a Rigidbody, then transform.GetComponent is not null. In fact transform.GetComponent() == GetComponent() == gameObject.GetComponent == someOtherComponent.GetComponent(). They are all the same thing.

I don’t know what the OP’s actual problem is, but this isn’t it.

Okay, if he doesn’t have a rigidbody on his object, then this is still a problem.

Let op explain more instead of leaping to help someone who clearly doesn’t put much effort in.

1 Like