A
A
abakhireva2019-01-27 14:21:32
C++ / C#
abakhireva, 2019-01-27 14:21:32

Unity3D throws an error in the character movement script. What's wrong?

Unity3D throws the following error: NullReferenceException: Object reference not set to an instance of an object
CharacterControllerScript.FixedUpdate () (at Assets/CharacterControllerScript.cs:29)
There is only one script in the game so far, I give it below. Please help me figure out the problem, I'm still new to this business and don't really understand what people write on the Internet.

using UnityEngine;
using System.Collections;

public class CharacterControllerScript : MonoBehaviour
{

    public float maxSpeed = 10f;
   
    private bool isFacingRight = true;
   
    private Animator anim;
    private Rigidbody2D rb;
    private bool isGrounded = false;
    public Transform groundCheck;
    private float groundRadius = 0.2f;
    public LayerMask whatIsGround;
    
  private void Start()
    {
        anim = GetComponent<Animator>();
    }

    private void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    
        anim.SetBool("Ground", isGrounded);

        const string Name = "vSpeed";
        anim.SetFloat(Name, rb.velocity.y);
       
        if (!isGrounded)
            return;
        
        float move = Input.GetAxis("Horizontal");
        
        anim.SetFloat("Speed", Mathf.Abs(move));

        {
            rb = GetComponent<Rigidbody2D>();
        }
        rb.velocity = new Vector2(move * maxSpeed, rb.velocity.y);

        if (move > 0 && !isFacingRight)
            Flip();
       
        else if (move < 0 && isFacingRight)
            Flip();
    }

    private void Update()
    {
       
        if (isGrounded && Input.GetKeyDown(KeyCode.Space))
        {
         
            anim.SetBool("Ground", false);
            rb.AddForce(new Vector2(0, 600));
        }
    }

    private void Flip()
    {
        isFacingRight = !isFacingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Griboks, 2019-01-27
@Griboks

{
            rb = GetComponent<Rigidbody2D>();
        }

remove the brackets

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question