How to tidy up my code for Unity 5 Basic Platformer
Hi guys,
I've been following a recent tutorial to set up a basic platformer. The script works, but it's a little untidy. So I thought I'd do the typical suggest to change the lengthy:
GetComponent ().velocity = new Vector2 (GetComponent ().velocity.x, jump);
to something shorter and more readable:
rb.velocity = new Vector2 (rb.velocity.x, jump );
But it just isn't working with the changes. Below is the full C# script:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
//Movement
public float speed;
public float jump;
float moveVelocity;
public Rigidbody rb;
bool IsGrounded = true;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update ()
{
//Jumping
if (Input.GetKeyDown (KeyCode.UpArrow) && (IsGrounded == true))
{
//rb.velocity = new Vector2 (rb.velocity.x, jump );
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
}
moveVelocity = 0;
//Left Right Movement
if (Input.GetKey (KeyCode.LeftArrow))
{
moveVelocity = -speed;
}
if (Input.GetKey (KeyCode.RightArrow))
{
moveVelocity = speed;
}
GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D> ().velocity.y);
Debug.Log(IsGrounded);
}
//Check if Grounded
void OnTriggerEnter2D()
{
IsGrounded = true;
}
void OnTriggerExit2D()
{
IsGrounded = false;
}
}
Any help or suggestions how I could improve the script would be appreciated.
Thanks, Jay.
Answer by Landern · Dec 04, 2015 at 01:59 PM
If you're using Rigidbody2d components on your GameObjects, i would go ahead and change your Start method to actually pull the same component type that is used throughout your code. Variable rb is probably not set to the component you want given the context of the rest of your script.
// Get Rigidbody2d not Rigidbody
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
Now that the right object type matches across the board you should be able to tighten things up.