Hello, I am having an issue regarding managing projectiles in my game.
The idea that I am trying to achieve is for a unit to fire a projectile which then follows the target until it hits it, triggering damage. If the target dies before the remaining bullets have reached it, those bullets will travel to the targets last location.
On my first unit (soldier), in order to attack I enable a pooled projectile at the location of solider and set it as a child of the target unit (demon). The projectile has a script which basically gets the target gameobject from the parent it’s attached to as a reference, then changes its parent to the _PooledItems gameobject. The reason for moving the projectile to another parent is because I want the bullets to persist even if the target demon is destroyed (any bullets still travelling disappear if I destroy the demon). So basically i get my target info from the parent transform, change the parent to something else then continue with my script which moves the projectile to my target:
void OnEnable ()
{
Transform parent = GameObject.Find("_PooledItems").transform;
targetObject = gameObject.transform.parent.gameObject;
gameObject.transform.SetParent(parent);
dest = targetObject.transform.position;
}
void Update ()
{
if (targetObject == null)
{
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, dest, Time.deltaTime * projectileSpeed);
if (gameObject.transform.position == dest)
{
gameObject.SetActive(false);
}
}
else
{
RotateTowards(targetObject.transform);
dest = targetObject.transform.position;
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, dest, Time.deltaTime * projectileSpeed);
if (gameObject.transform.position == dest)
{
UnitEngine.takeDamage(damage, targetObject);
gameObject.SetActive(false);
}
}
Problem:
I am using the parent of the projectile gameobject as a means to get the target info because I cannot think of how else to pass it this knowledge. This causes issues where target gameobjects are destroyed before another bullet has moved to a different parent causing some bullets to go missing.
Ideally I would like to enable a projectile gameobject, give it the knowledge of what unit shot it and what unit it’s target is.
Any ideas how to solve this problem?
As a bonus criteria, the solution will be potentially run thousands of times at once (think bullet hell, hence the object pooling) so I would like to avoid lengthy function calls if possible.