wait, what?

I’m apparently getting a null reference exception on a variable which was filled on the line before, how the heck is this happening? O_o

using UnityEngine;
using System.Collections;

public class basicdamage : MonoBehaviour {
	public float hp;
	public Transform prefab;
	Rigidbody created;
	// Use this for initialization
	void Damage (float d) {
		hp -= d;
		if (hp <= 0)
		{
			foreach (Transform child in transform)
			{
				Destroy(child.gameObject);
			}
			collider.enabled = false;
			created = Instantiate(prefab,transform.position,transform.rotation) as Rigidbody;
			Debug.Log(created);[COLOR="#4169e1"] // returns null for some reason.[/COLOR]
			created.velocity = rigidbody.velocity; [COLOR="#4169e1"]// null reference exception here.[/COLOR]
			Destroy(gameObject);
		}
	}
}

Because you are casting your instantiated object to a RigidBody and the object type returned cannot be cast to a RigidBody, therefore the created variable is assigned as null. Always check for null after using as unless you are absolutely sure it will never be, and change how your code instantiates and casts to RigidBody.

created will be null if Instantiate was called on a prefab that wasn’t a Rigidbody. The ‘as’ cast returns null when it can’t be cast as a Rigidbody.

call Debug.Log(Instantiate(…).GetType().FullName); to determine what it is exactly you are working with as a Prefab.

Also “wait, what?” is a horrible thread title, and displays no information about what it is your thread is talking about (which is the purpose of a thread title).

What he said.

I don’t help non descriptive postings which don’t have an explanatory title.

My overwhelming desire to show off what I know is larger than my desire to teach others not to use horrible, non-productive habits. But I can still complain about it after the fact :P.

.>

well thanks, didn’t know that instantiate couldn’t cast to rigidbody and that I needed to cast it to transform instead.

Instantiate can cast to Rigidbody, so long as that is what you pass in in the first place.

Look at your own code:

public Transform prefab;
Instantiate(prefab,transform.position,transform.rotation) as Rigidbody;

You told Instantiate to create a Transform, and then tried to turn it into a Rigidbody. If you gave it a Rigidbody, and tried to turn it into a Transform it’d do the same thing.

Instantiate clones whatever you tell it to clone, but trying to clone an apple and expecting an orange is never going to work.

That is a great analogy. :slight_smile: