Reputation: 758
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?
Upvotes: 0
Views: 1135
Reputation: 12258
As detailed by Kapol, your problem does appear to be your attempt to cast a GameObject
to a RigidBody2D
with the line:
USBInstance = Instantiate (USBPrefab, newTransform.position, Quaternion.identity) as Rigidbody2D;
Since this cast will fail (the two types really are quite different), this line of code basically works out to USBInstance = null;
, and trying to call any methods on it will give you a NullReferenceException
.
Seeing as you're already calling GetComponent<Rigidbody2D>()
on the next line, there's no need to try to cast the result of the Instantiate()
to anything; just leave it as a GameObject
:
USBInstance = Instantiate (USBPrefab, newTransform.position, Quaternion.identity);
Hope this helps! Let me know if you have any questions.
Upvotes: 1
Reputation: 6463
In my opinion, the problem lays in the following line:
USBInstance = Instantiate (USBPrefab, newTransform.position, Quaternion.identity) as Rigidbody2D;
After calling Instantiate
, you try to cast the result to an instance of Rigidbody2D
using the as
operator. Now here is what Microsoft has to say about this operator:
The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.
It looks like the conversion is not possible and therefore USBInstance
is null
when you call GetComponent
on it.
Upvotes: 0
Reputation: 1566
Really you need to do more research before you post a question. This should be fairly obvious to any programmer after their first couple OOP programs. You are using an object that has no value. Perhaps your transform is never made or your Quaternion doesn't exist. Something of the sort
Upvotes: 0