I used the script from this thread:
But it gives me an error saying
“UnityEngine.Component' does not contain a definition for velocity’ and no extension method velocity' of type UnityEngine.Component’ could be found.”
Can anyone help me out with this?
PGJ1
2
The script is old, you cannot access the rigidbody that way anymore. Try to replace it with; GetComponent()
Thank you for your advice! But the bottom line of code doesn’t work if I just replace it. What should I do for that instead?
The standard way to interact with components is to use a variable to hold a reference to a component, and then use that variable throughout the class:
using System;
using UnityEngine;
public class walk2D : MonoBehaviour {
public float maxWalkSpeed;
public float jumpSpeed;
private Vector3 playerVelocity;
private Rigidbody2D rigidbodyComponent;
private void Awake() {
rigidbodyComponent = GetComponent<Rigidbody2D>();
}
private void Start() {
playerVelocity = Vector3.zero;
}
private void Update() {
playerVelocity.x = Input.GetAxis("Horizontal") * maxWalkSpeed;
if(Input.GetKeyDown(KeyCode.Space)) {
playerVelocity.y = jumpSpeed;
} else {
playerVelocity.y = rigidbodyComponent.velocity.y;
}
rigidbodyComponent.velocity = playerVelocity;
}
}