Search Unity

Place popup-score at enemy position

Discussion in '2D' started by drpelz, Jul 3, 2018.

  1. drpelz

    drpelz

    Joined:
    Dec 7, 2017
    Posts:
    29
    Hi,

    I’d like to place a popup-score at the position where an enemy has been destroyed. I'm developing a 2D-game in Unity3D.

    So far the popup-score gets rendered inside of the canvas but the position seems to have an offset. How do I place the popup-score at the position of the destroyed enemy exactly?

    This is the c#-class that fades the score:

    Code (CSharp):
    1. public class FloatAndFade : MonoBehaviour {
    2.  
    3. Text text;
    4.  
    5. public float fadeDuration = 2.0f;
    6. public float speed = 2.0f;
    7.  
    8. void Start () {
    9.    text = this.GetComponent<Text>();
    10.    StartCoroutine(Fade());
    11. }
    12.  
    13. public IEnumerator Fade () {
    14.  
    15.    float fadeSpeed = (float)1.0 / fadeDuration;
    16.    Color c = text.color;
    17.  
    18.    for (float t = 0.0f; t < 1.0f; t += Time.deltaTime * fadeSpeed) {
    19.        c.a = Mathf.Lerp(1, 0, t);        
    20.        text.color = c;
    21.        yield return true;      }
    22.  
    23.    Destroy (this.gameObject);
    24. }
    25.  
    26. void Update() {
    27.    this.transform.Translate(Vector3.up * Time.deltaTime * speed);
    28.    }
    29. }
    This is the FloatScore-method that places the popup-score inside of the canvas:
    Code (CSharp):
    1. void FloatScore () {
    2.    GameObject popupScore = (GameObject)Instantiate (floatScore);
    3.  
    4.    popupScore.transform.position = Camera.main.WorldToScreenPoint(this.transform.position);
    5.  
    6.    popupScore.transform.SetParent (canvas.transform, false);
    7. }
    These are the settings for the canvas:



    This is the gameplay with the popup-score:

     
  2. Raali_Oloth

    Raali_Oloth

    Joined:
    Jul 29, 2013
    Posts:
    22
    try to determine values of offset, it can be anchors or something
    try to set popupScore anchoredPosition instead of position
    try to setParent before setting anchored position

    worldToScreenPoint returns values from 0,0 to screen size , where 0,0 is left bottom corner, but in your case 0,0 can be at center of canvas. It difficult to say without a project
     
  3. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    892
    Use World Space for the Text's Canvas, then it will use the scene's coordinate system. And parent the Canvas to the enemy at when you Instantiate it.
     
  4. drpelz

    drpelz

    Joined:
    Dec 7, 2017
    Posts:
    29
    Thanks for the tips. I found this tutorial and now it works like a charm:
     
unityunity