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!