Floating Damage Text Above Object on Hit

When my asteroids are hit by a bullet, I would like to show the damage done as a GUIText popping up on top of them. I have a script for the asteroids, where the collisions are detected and and an instance of the GUIText is called. This works fine, as far as I know. I can make it pop up in the center of the screen if I set the tempFloatingDamage instantiate coords to Vector3(0.5f,0.5f,0). But when I try to calculate the position of the asteroid and spawn it there, I get “NullReferenceException: Object reference not set to an instance of an object”. I’m not properly grabbing the transform.position for that particular instance of the asteroid. It should be simple, but my brain just won’t wrap around it. Here is my code:

using UnityEngine;
using System.Collections;

public class IsAsteroid : MonoBehaviour
{
	public GameObject explosion;
	public float health;
	public GameObject FloatingDamagePrefab;



	void Start ()
	{

	}

	void Update ()
	{
		if (health <= 0)
		{
			Destroy(gameObject);
		}

	}
	
	void OnTriggerEnter (Collider other)
	{


		if (other.tag == "Bullet")
		{

			health = health - 10;
			Vector3 textLocation = Camera.main.WorldToScreenPoint(transform.position);
			textLocation.x /= Screen.width;
			textLocation.y /= Screen.height;
			Transform tempFloatingDamage = (Transform)Instantiate(FloatingDamagePrefab, textLocation, Quaternion.identity);
			tempFloatingDamage.GetComponent<FloatingDamageScript>().DisplayDamage(((int)10).ToString());
		}


		if (explosion != null)
		{
			Instantiate(explosion,transform.position,transform.rotation); //Create a new explosion instance when hit
		}


	}
}

This is the line giving me trouble: Vector3 textLocation = Camera.main.WorldToScreenPoint(transform.position);

Any help would be greatly appreciated. Thank you!

I see a problem here, and a potential problem here.

First, you are Instantiating a game object but you are casting the result to a transform. Don’t do that. ‘FloatingDamagePrefab’ and ‘tempFloatingDamage’ need to be of the same type…they can be either Transform or GameObject. Make the line:

        GameObject tempFloatingDamage = Instantiate(FloatingDamagePrefab, textLocation, Quaternion.identity) as GameObject;

If this does not fix your problem, next make sure that ‘FloatingDamagePrefab’ has been assigned, and that you don’t have another copy of this script somewhere.

Further down the road based on your question, you will want to place your text at the point of damage. Note that GUIText lives in Viewport space, so yo will need to do a Camera.WorldToViewport() conversion on the hit point to get the position.