Why isn't my projectile object being instantiated with the given values?

33 Views Asked by At

In this game, this crystal ball finds the closest enemy and sets it as a "target." Once the target is within a certain distance, it's supposed to start firing bolts.

Everything is working up to the bolts. I'm trying to set the bolt's "target" to the target of the crystal ball, as well as the bonus damage values taken from the player stats.

Here is the code I'm using to instantiate the bolts.

 if (distance <= maxDistance)
    {
        GameObject bolt = Instantiate(magicBolt, new Vector2(transform.position.x, transform.position.y ), Quaternion.identity);
        bolt.GetComponent<AttackDamage>().bonusMagicDamage = stats.magicBallDamage;
        bolt.GetComponent<MagicBallFire>().target = target;
    }

When the bolts actually get instantiated, they have no target and not bonus damage value. enter image description here

enter image description here

I'm confused because I've instantiated objects and updated their variables in the exact same way, so why isn't it working for this?

Here's the full script for the crystal ball:

void Start()
{
    InvokeRepeating("FireProjectile", 0, fireRate);
}

void Update()
{
    FindClosestEnemy();
}

void FindClosestEnemy()
{
    float distanceToClosestEnemy = Mathf.Infinity;
    GameObject closestEnemy = null;
    GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Enemy");

    foreach (GameObject currentEnemy in allEnemies)
    {
        float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
        if (distanceToEnemy < distanceToClosestEnemy)
        {
            distanceToClosestEnemy = distanceToEnemy;
            closestEnemy = currentEnemy;
        }
    }
    target = closestEnemy;
}

void FireProjectile()
{
    if (target == null)
    {
        return;
    }
    
    distance = Vector2.Distance(transform.position, target.transform.position);
    
    if (distance <= maxDistance)
    {
        GameObject bolt = Instantiate(magicBolt, new Vector2(transform.position.x, transform.position.y ), Quaternion.identity);
        bolt.GetComponent<AttackDamage>().bonusMagicDamage = stats.magicBallDamage;
        bolt.GetComponent<MagicBallFire>().target = target;
    }
}
0

There are 0 best solutions below