I keep getting compiler errors on my code, please help. (C#)
using UnityEngine; using System.Collections;
public class ThiefControllerScript : MonoBehaviour { public float maxSpeed = 7f; bool facingRight = true; bool facingLeft = true;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 700f;
void Start ()
{
anim = GetComponent<Animator>();
}
void FixedUpdate ()
{
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
anim.SetBool ("Ground", grounded);
anim.SetFloat ("vSpeed", GetComponent<Rigidbody2D>().velocity.y);
float move = Input.GetAxis ("Horizontal");
anim.SetFloat ("Speed", (move));
GetComponent<Rigidbody2D>().velocity = new Vector2 (move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (!facingRight)
anim.SetBool ("FLeft", (false));
else if (facingRight)
anim.SetBool ("FRight", (false));
if (!facingLeft)
anim.SetBool ("FLeft", (true));
else if (facingLeft)
anim.SetBool ("FRight", (true));
}
void Update()
{
if (grounded && Input.GetKeyDown(KeyCode.Space))
anim.SetBool ("Ground", false);
Rigidbody2D.AddForce (new Vector2(0, jumpForce));
}
}
This would be much easier to answer if you posted the error you're getting, as they generally mention what line the error is on and in which file, as well as what kind of error it is.
Unrelated: If the two lines under your if statement in the update function are both meant to be part of that if branch, you'll need to put {} around that block. This isn't causing your error, but it'll cause unexpected runtime behaviour until it gets fixed.
Answer by JHobsie · Mar 07, 2017 at 04:54 AM
The line is at 'Rigidbody2D.AddForce (new Vector2(0, jumpForce));'
AddForce is not a static method, but an instance method. So you need to get a reference to the RigidBody2D component.
Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();
rigidbody.AddForce(new Vector2(0, jumpForce));
Note: You may want to store a reference to the rigidbody just like how you are doing with the Animator component.
Your answer
Follow this Question
Related Questions
Error with String in code 1 Answer
NULL REFERENCE DRVING ME INSANE!!! HELP!!!! 1 Answer
Unity namespace cannot be found (C# MonoDevelop) 1 Answer
Failed to Copy Assembly-CSharp.dll on Script-Compilation 0 Answers
C# Compile Error 0 Answers