Rigidbody2D Null Reference Exception after Instantiation
I need a Unity game engine specific answer.
So basically, I'm writing a script that controls a spawner. It is pretty generic, and basically what it does is apply a force to an instantiated rigidbody after it is spawned. But for some reason, every time I spawn the object for the first time, Unity throws a NullReferenceException error. I checked my code for errata, but I think it is fine. Anyone got tips?
BTW, the exact error message was :
NullReferenceException: Object reference not set to an instance of an object USBSpawner+c__Iterator0.MoveNext () (at Assets/Scripts/USBSpawner.cs:24)
Code:
using UnityEngine;
using System.Collections;
public class USBSpawner : MonoBehaviour {
public static bool isActive = true;
public GameObject USBPrefab;
public float spawnDelay = 5f;
public Vector2 throwForce;
void Start() {
StartCoroutine(SpawnUSB());
}
IEnumerator SpawnUSB () {
yield return new WaitForSeconds(spawnDelay);
if(isActive) {
var newTransform = transform;
Rigidbody2D USBInstance;
USBInstance = Instantiate (USBPrefab, newTransform.position, Quaternion.identity) as Rigidbody2D;
USBInstance.GetComponent<Rigidbody2D>().velocity = throwForce;
}
StartCoroutine(SpawnUSB());
}
}
Got any ideas?