Eric Petakchyan
Eric Petakchyan

Reputation: 11

How to get gameobject position from another script

I have a bullet that touches the enemy. Then a text appears, which, thanks to the animation, shows how much life was taken from the enemy.

When I throw the prefab of that text on the enemy, so that the texts appear on the enemy via Instantiate, when the enemy destroys, the texts are quickly lost along with it.

 private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.CompareTag("Bullet"))
    {
        
        if (FlyingTextPrefab)
        {
            ShowFlyingText();
        } 

        Destroy(collision.gameObject);

    }
   
     
}
void ShowFlyingText()
{
    var go = Instantiate(FlyingTextPrefab, transform.position, Quaternion.identity, transform);
    go.GetComponent<TMPro.TextMeshPro>().text = demage.ToString();
}

I moved Instantiate to another code to work independently of the enemy, but now I can not make the text appear from the position of the enemy.

Enemy Code

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.CompareTag("Bullet"))
    {
        PlayerPrefs.SetString("flyingText", "true");
        
        Destroy(collision.gameObject);

    }

}

Text Instantiate

void Update()
{
    if (PlayerPrefs.GetString("flyingText") == "true")
    {
        ShowFlyingText();
        PlayerPrefs.SetString("flyingText", "false");
    }
}
void ShowFlyingText()
{
    var go = Instantiate(FlyingTextPrefab, Enemy.transform.position, Quaternion.identity, transform); // how to get Enemy positions, its dont works normally
    go.GetComponent<TMPro.TextMeshPro>().text = 50.ToString();
}

Upvotes: 0

Views: 174

Answers (2)

Mohammed Thaier
Mohammed Thaier

Reputation: 173

Don't spawn the text as child to the enemy Instead of typing

var go = Instantiate(FlyingTextPrefab, transform.position, Quaternion.identity, transform);

Type

 var go = Instantiate(FlyingTextPrefab, transform.position, Quaternion.identity);

In this way the text will instantiated in the world instead of instantiated as child to the enemy object

Upvotes: 0

derHugo
derHugo

Reputation: 90714

And why not simply not spawn it as child of the enemy but still at its position:

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.CompareTag("Bullet"))
    {
        
        if (FlyingTextPrefab)
        {
            ShowFlyingText();
        } 

        Destroy(collision.gameObject);
    }    
}

void ShowFlyingText()
{
    var go = Instantiate(FlyingTextPrefab, transform.position, Quaternion.identity);
    go.GetComponent<TMPro.TextMeshPro>().text = demage.ToString();
}

without passing in the transform as the parameter parent.

Parent that will be assigned to the new object.

Upvotes: 1

Related Questions