Search code examples
c#unity-game-engineinstantiation

Instantiated Object Not Moving


Below is a class attached to a prefab object that gets Instantiated in the game but an up force is not applied to the object which the code below is trying to do instead I am getting this error.

NullReferenceException: Object reference not set to an instance of an object at line 15

Which is

rb.GetComponent<Rigidbody2D>();

.

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightBulbLeft : MonoBehaviour {

//public GameObject LeftLB;


Rigidbody2D rb;

// Use this for initialization
void Start()
{
    rb.GetComponent<Rigidbody2D>();
    rb.AddForce(Vector2.up * 15f, ForceMode2D.Impulse);
}

}


Solution

  • void Start()
    {
      rb = GetComponent<Rigidbody2D>();
      rb.AddForce(Vector2.up * 15f, ForceMode2D.Impulse);
    }
    

    The GetComponent<T> method returns the component attached to an object. You need to assign rb to your Rigidbody before applying the force.