My SetParent doesn't do what I want

Hi fellow developers :slight_smile:

I wrote some code that instantiates a GameObject that shows the amount of damage you did. It worked, but it didn’t work perfectly so I changed some stuff. Now every time I hit an enemy it spawns the text at the same enemy (like I hit enemy 2 but it spawns the text at enemy 1) :frowning:

This is the function that I put on the canvas of the enemy prefab

`
    public void Initcbt(string damage)
    {
        GameObject temp = (GameObject)Instantiate(cbt);
        RectTransform tempRect = temp.GetComponent();
        temp.transform.SetParent(transform);
        tempRect.transform.localPosition = cbt.transform.localPosition;
        tempRect.transform.localScale = cbt.transform.localScale;
        tempRect.transform.localRotation = cbt.transform.localRotation;
        temp.GetComponent().text = damage;
        Destroy(temp.gameObject, 1f);
    }
`

I’m not sure if I’m using setParent right, I did it different but Unity was stalking me to death that I should use this one.

the script I wrote to for doing damage on the player is this:

`
if (Input.GetButtonDown("Hit1") && Stamina.stam.curStamina >= 20)
{
    Stamina.stam.curStamina -= takeStamina;
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))
    {
        distance = hit.distance;
        //Debug.DrawLine(transform.position, hit.transform.position, Color.red);
        if (distance < maxDistance)
        {
            damage = Random.Range(45.0f, 60.0f) + (PlayerStates.playerStates.level * 5);
            EnemyHealth.enemyHP.ApplyDamage(damage);
         }
    }
}  
`

it shoots a ray because i’m still waitng on my artists to finish the player (i’m sure you know the problem)

this is the function the player calls when it hits the enemy:

public void ApplyDamage(float damage)
{
    health -= damage;
    CombatText.combatText.Initcbt(damage.ToString());
}

Help me please :slight_smile:

2 Answers

2

Your script looks fine. The only issue I could possibly think of is if you are not calling Initcbt on
the correct enemy. You may be calling it on Enemy1 when you are damaging Enemy2.

If this is not the case, please let me know. Also, please share the script where you call Initcbt.

Hello @danivdwerf , I think you should change your approach to show UI on player . Because Canvas always recalculate there position according to there settings . So I think you write down a script that update the UI panel where data is shown according to player screen position without making it parent.