In trying to make a jumping script in C#, I ran across this error:
error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody.velocity’
This is my program:
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour {
public float JumpHeight = 8.0f;
private bool isFalling = false;
void Update () {
bool jump = Input.GetAxis("Jump") != 0;
if (jump && isFalling == false)
{
Vector3 velocity = Rigidbody.velocity;
velocity.y += JumpHeight;
Rigidbody.velocity = velocity;
isFalling = true;
}
}
void OnCollisionStay ()
{
isFalling = false;
}
}
It would be very helpful if you could help me…
Thanks
Wait… It has to be this way…
void Update () {
bool jump = Input.GetAxis("Jump") != 0;
if (jump && isFalling == false)
{
Vector3 velocity = GetComponent<Rigidbody>().velocity;
velocity.y += JumpHeight;
GetComponent<Rigidbody>().velocity = velocity;
isFalling = true;
}
}
Or this way
public RigidBody rig;
void Update () {
bool jump = Input.GetAxis("Jump") != 0;
if (jump && isFalling == false)
{
Vector3 velocity = rig.velocity;
velocity.y += JumpHeight;
rig.velocity = velocity;
isFalling = true;
}
}
Honestly mate I’d ditch that jump bool and getaxis as it seems to be a really strange way to find out if space is being pressed you really only need this…
if (Input.GetKeyDown("space") && isFalling == false) {
I’ve converted this to an answer so you can accept as the actual solution is pretty drawn out over a lot of comments. Really I’d upvote the other answer as well, always good to show appreciation if someone has taken time to help out.
Edit: Sorry this not an answer.
I added a “Debug.Log” statement that tells me when I am in the if statement and when I am touching an object.
This is my program:
using UnityEngine;
using System.Collections;
public class Jump : MonoBehaviour {
public float JumpHeight = 8.0f;
private bool isFalling = false;
public Rigidbody rig;
void Update () {
bool jump = Input.GetAxis("Jump") != 0;
if (jump && isFalling == false)
{
Vector3 velocity = rig.velocity;
velocity.y += JumpHeight;
rig.velocity = velocity;
isFalling = true;
Debug.Log("Jump");
}
}
void OnCollisionStay ()
{
isFalling = false;
Debug.Log("Grounded");
}
}
When I press space the first time it prints it out in the console. Any other time it does not work. Also, it never prints out “Grounded”. It should when I touch an object. Could you give me a working jumping program or fix mine?
Thanks.