Create prefab of floating text
- Create new UI Text: Component - UI - Text, named PopupText
- PopupText property
- Rect Transform: Anchor: Middle + center
- Set value of width and height
- Text: Alignment: middle and center
- Insert Outline component to make it better UI
- Add Animator controller component
- Make a great animation for the text (curve moving, etc.)
- Create new GameObject (child of Canvas), make it PopupText's parent, named PopupTextParent, make a prefab of it
- Move PopupTextParent to folder Resources/Prefabs (wherever location of the prefab, it should be in the Resource folder)
Code
- FloatingTextController class
// find the main canvas, named CanvasUI
parent = GameObject.Find("CanvasUI").GetComponent<RectTransform>();
if (popupText == null) {
// PopupTextParent is a gameobject which contains a text with animation + and animator controller
popupText = Resources.Load ("Prefabs/PopupTextParent") as GameObject;
// popupText = Resources.Load ("Prefabs/PopupText") as GameObject;
Debug.Log ("Loaded popup text parent from resources.");
}
//create an instance of the text prefab
GameObject instance = Instantiate(popupText);
//convert it's called location to screenspace + a random distance between min and max
Vector2 screenPos = Camera.main.WorldToScreenPoint(
new Vector2(location.position.x + Random.Range(min,max), location.position.y + Random.Range(min,max)));
//parent that instance to the canvas
instance.transform.parent = parent;
//set the instance's position to screenPos
instance.transform.position = screenPos;
//set the text to passed
instance.GetComponentInChildren<Text>().text = damage.ToString();;
//get anim clip length and destroy it at end of clip
Animator anim = instance.GetComponentInChildren<Animator>();
//grabs current animator clip and store it in array
AnimatorClipInfo[] clipInfo = anim.GetCurrentAnimatorClipInfo(0);
//floating text disappears
Destroy(instance, clipInfo[0].clip.length);
}
0 comments:
Post a Comment