- Home /
"NullReferenceException: Object reference not set to an instance of an object" with instantiate C#
This must be something super simple that I'm missing but I couldn't find it for the life of me.
I have pasted my entire script, but the error is on line 48 when I try to add force to the instantiated object. The object has a rigidbody attached.
using System.Collections;
public class slimy : MonoBehaviour {
public Rigidbody coin;
float hp = 10;
float defence = 1;
public GameObject[] drops;
public int[] droprate;
public int mincoin = 1;
public int maxcoin = 3;
public Transform coinpos;
public float moneyspread = 100;
void OnCollisionEnter2D(Collision2D coll) {
hitarrow ();
deathcheck ();
}
void hitarrow(){
float initial = playerattack.calculatedmg ("arrow");
float dmg = initial / defence;
hp -= dmg;
Debug.Log ("Damage: " + dmg);
}
void deathcheck(){
if (hp <= 0) {
drop();
Destroy (gameObject, 0.001f);
}
}
void drop(){
for(int i = 0; i < (Random.Range (mincoin, maxcoin)); i++){
float coinforce = Random.Range(100f, 350f);
float coinrot = Random.Range(0f, 360f);
coinpos.localRotation = Quaternion.Euler(0, 0, coinrot);
coinpos.position = transform.position;
/*
Rigidbody2D shot;
shot = Instantiate(coin, coinpos.position, coinpos.rotation) as Rigidbody2D;
shot.velocity = transform.TransformDirection(Vector2.up * coinforce);
*/
Rigidbody clone;
clone = Instantiate(coin, transform.position, coinpos.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.up * 10);
}
}
}
Answer by AndyMartin458 · Jul 07, 2014 at 07:12 AM
The object you are creating has a Rigidbody, but it is not a Rigidbody. That is why the cast is not working out for you. You should instantiate the coin prefab as a GameObject and then use GetComponent to get the Rigidbody.
GameObject go = Instantiate(coin, transform.position, coinpos.rotation) as GameObject;
Rigidbody clone = go.GetComponent<Rigidbody>();
clone.velocity = transform.TransformDirection(Vector3.up * 10);
You can find out more information here. http://docs.unity3d.com/Manual/InstantiatingPrefabs.html
Your answer
Follow this Question
Related Questions
Can't find source of trigger Null Reference Exception 1 Answer
Instantiate object in C# 1 Answer
Can´t instantiate objects in list correctly 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer