Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Turret firing on Enemies

Discussion in 'Scripting' started by Saxi, May 29, 2014.

  1. Saxi

    Saxi

    Joined:
    Jun 28, 2013
    Posts:
    381
    I am trying to build a prototype Tower Defense game and figuring out how to create a turret that fires on enemies.

    I have a single test enemy that is following a path along three way points.
    I have a sphere collider on the turret as a trigger and monitoring TriggerEnter and Exit.

    On Enter, I add the other game object to the target list.
    On exit, I remove the other game object from the target list.

    On update, I check if there is any objects in the list, if there is, I fire on the first target in the list.

    On the enemy, I have an EnemyHealth script with takeDamage(int) and inside there it destroys itself if it takes gets to 0 or lower.

    The targeting works, but if the enemy destroys itself, my targets list still has a reference to the object and it never gets removed which of course causes problems.

    I would like to use a delegate as I understand it to be a lot faster than sendmessage but I am not sure where I should put it and how I should fire it.

    I am thinking I would have the delegate on the turret, and the enemy would subscribe to it and call it's function. But this poses two problems. My targeting system is from the turrets perspective, and I am managing the list there. So I still have the problem of notifying the turret to update its target list.

    I'm having a hard time figuring out the best way to solve this and if I should scrap the entire target list on the turret idea, but that part seems to be ok. I just need a way to have the turret notify the enemy it is taking damage, and the enemy letting the turret know it is dead. Is there a way to do this with one delegate, or is the problem that I need two and one of each to notify each other?

    Or is there a better way to do all this?
     
  2. Ivam

    Ivam

    Joined:
    May 29, 2014
    Posts:
    11
    I´m not an expert but...

    you must have a variable with the GameObject of the target. When the target dies (destroy function) the variable will be null and you can just select the new target.
     
  3. Gentleman Whale

    Gentleman Whale

    Joined:
    Apr 26, 2014
    Posts:
    6
    Use physics.overlapsphere for targeting and if the target is no longer within the overlapping sphere set it to find another target or to NULL?
     
  4. Saxi

    Saxi

    Joined:
    Jun 28, 2013
    Posts:
    381
    Thanks, that pointed me in the right direction. I did a check to see if there is more than 0 objects in the list and object 0 is null to remove 0, then do what I need to do on 0.