Search Unity

Scripting Gravity 2/8 Tutorial - Code error

Discussion in 'Community Learning & Teaching' started by Cedhric, Aug 12, 2017.

  1. Cedhric

    Cedhric

    Joined:
    Aug 4, 2017
    Posts:
    2
    Hi, I'm having a problem with the Scripting Gravity [2/8] tutorial:



    I get the following error in the console:

    NullReferenceException: Object reference not set to an instance of an object
    PhysicsObject.Movement (Vector2 move) (at Assets/PhysicsObject.cs:40)
    PhysicsObject.FixedUpdate () (at Assets/PhysicsObject.cs:35)

    I can't see how my code differs from the example:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PhysicsObject : MonoBehaviour {
    6.  
    7.     public float gravityModifier = 1f;
    8.  
    9.     protected Rigidbody2D rb2d;
    10.     protected Vector2 velocity;
    11.  
    12.     void onEnable()
    13.     {
    14.         rb2d = GetComponent<Rigidbody2D> ();
    15.     }
    16.  
    17.     // Use this for initialization
    18.     void Start () {
    19.        
    20.     }
    21.    
    22.     // Update is called once per frame
    23.     void Update () {
    24.        
    25.     }
    26.  
    27.     void FixedUpdate()
    28.     {
    29.         velocity += gravityModifier * Physics2D.gravity * Time.deltaTime;
    30.  
    31.         Vector2 deltaPosition = velocity * Time.deltaTime;
    32.  
    33.         Vector2 move = Vector2.up * deltaPosition.y;
    34.  
    35.         Movement (move);
    36.     }
    37.  
    38.         void Movement(Vector2 move)
    39.     {
    40.         rb2d.position = rb2d.position + move;
    41.     }
    42.  
    43. }
    44.  
    Using Unity 2017.1.0f3 personal.
     
  2. Cedhric

    Cedhric

    Joined:
    Aug 4, 2017
    Posts:
    2
    I found the problem - Line 12
    Code (CSharp):
    1. void onEnable()
    Should be a capital 'O' at OnEnable
    Code (CSharp):
    1. void OnEnable()
    So the rb2d variable wasn't being assigned, as OnEnable wasn't doing anything, and onEnable was never called.

    A swine to track down, but taught me a few things. Onwards and upwards!
     
  3. TheDragonBaby

    TheDragonBaby

    Joined:
    Jul 18, 2019
    Posts:
    1
    had the same issue lol feel like an idiot :p