In my game I’d like to give the user points for accomplishing special tasks. I would like these points to appear on the screen at the location where the special task occurs and have them float upwards and gradually fade out. I was thinking that I could achieve this with a particle system but I do not know how I would be able to make the bonus points particles because the points are calculated at runtime. Obviously I can’t make particles for every possible number of points a user can score.
Does anyone know how I can achieve this with or without a particle system?
If you only need the text to appear, float up, and fade out, you can solve this by spawning a 3d text object with a script attached to it that : orients it to the camera automatically every frame, rises upwards on the y axis every frame, and changes the text alpha every frame. When the alpha reaches zero, the script must also delete the game object.
Here is a c# script that does all that for you. To use it you need to:
make a 3d Text prefab object
assign this script to it
instantiate the prefab every time you need to spawn a rising number.
after instantiating the prefab, get the RisingText component, and call its setup method
The script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(TextMesh))]
public class RisingText : MonoBehaviour
{
// private variables:
Vector3 crds_delta;
float alpha;
float life_loss;
Camera cam;
// public variables - you can change this in Inspector if you need to
public Color color = Color.white;
// SETUP - call this once after having created the object, to make it
// "points" shows the points.
// "duration" is the lifespan of the object
// "rise speed" is how fast it will rise over time.
public void setup(int points, float duration, float rise_speed)
{
GetComponent<TextMesh>().text = points.ToString();
life_loss = 1f / duration;
crds_delta = new Vector3(0f, rise_speed, 0f);
}
void Start() // some default values. You still need to call "setup"
{
alpha = 1f;
cam = Camera.main;
crds_delta = new Vector3(0f, 1f, 0f);
life_loss = 0.5f;
}
void Update ()
{
// move upwards :
transform.Translate(crds_delta * Time.deltaTime, Space.World);
// change alpha :
alpha -= Time.deltaTime * life_loss;
renderer.material.color = new Color(color.r,color.g,color.b,alpha);
// if completely faded out, die:
if (alpha <= 0f) Destroy(gameObject);
// make it face the camera:
transform.LookAt(cam.transform.position);
transform.rotation = cam.transform.rotation;
}
}