What is wrong with this code?
Hey guys, so every time i try to play my 2d platformer it says all errors must be cleared before playing exact: Assets/Scripts/PlayerController.cs(17,13): error CS0619: UnityEngine.Component.rigidbody2D' is obsolete:
Property rigidbody2D has been deprecated. Use GetComponent() instead. (UnityUpgradable)'
Assets/Scripts/PlayerController.cs(17,25): error CS1061: Type UnityEngine.Component' does not contain a definition for
velocity' and no extension method velocity' of type
UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
Here is my code for gravity:
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
public float jumpHeight;
void Start () {
}
void Update () {
if(Input.GetKeyDown (KeyCode.UpArrow))
{
rigidbody2D.velocity = new Vector2(0, jumpHeight);
}
if (Input.GetKey (KeyCode.RightArrow))
{
rigidbody2D.velocity = new Vector2(moveSpeed, 0);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
rigidbody2D.velocity = new Vector2(-moveSpeed, 0);
}
}
}
Answer by Ahndrakhul · Jul 01, 2016 at 02:37 AM
I think you need to get a reference to the rigidbody2D before you use it. Either you can change all of the lines that use rigidbody2D.velocity
to GetComponent<rigidbody2D>().velocity
, or you can do something like this:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
rigidbody2D rB2D; //<-- rigidbody2D reference
public float moveSpeed;
public float jumpHeight;
void Start ()
{
rB2D = GetComponent<rigidbody2D>(); //<-- get rigidbody2D and assign to rB2D
}
void Update () {
if(Input.GetKeyDown (KeyCode.UpArrow))
{
rB2D.velocity = new Vector2(0, jumpHeight); //<-- use rB2D variable
}
if (Input.GetKey (KeyCode.RightArrow))
{
rB2D.velocity = new Vector2(moveSpeed, 0); //<-- use rB2D variable
}
if (Input.GetKey (KeyCode.LeftArrow))
{
rB2D.velocity = new Vector2(-moveSpeed, 0); //<-- use rB2D variable
}
}
}
Thank you sir.I missed this addendum in the Tutorial. Wasted quite a bit of time due to the fact that my code was exactly the same as in the Tutorial but it didn't work! I also started a questions on this... http://answers.unity3d.com/questions/1377616/error-cs-1061-space-shooter-tutorial-code-for-play.html
Answer by Raveerojh · Apr 03, 2017 at 07:48 AM
GetComponent(); is not corrected, so should be GetComponent();