Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Problem with my bomber enemies

Discussion in 'Scripting' started by Airmand, Jul 25, 2011.

  1. Airmand

    Airmand

    Joined:
    Jan 27, 2011
    Posts:
    139
    Ive got multiple enemies of the same prefab in my scene. My problem is that when the first enemy gets within 4 units of the player it blows up and does what it is supposed to do. However, when the next ones get to the player they only come up to him and stop. They dont take away from player health and they dont explode.

    Code (csharp):
    1.  var player : Transform;
    2. var explosion : ParticleEmitter;
    3.  
    4.  
    5. function Update () {
    6.     if(player) {
    7.         var dist = Vector3.Distance(player.position, transform.position);
    8.         if(dist <= 4){
    9.             Destroy(gameObject);
    10.             PlayerHealth.playerhealth -= 4;
    11.             Instantiate(explosion, transform.position, transform.rotation);
    12.         }
    13.     }
    14. }
     
  2. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    How are these objects created in the scene?

    It seems to me if they are instantiated and you are not fulfilling "player" then they wont know what the player is. hence it's not a good thing to incorporate "player" into a script, or if you do, tag the player as "Player" and use something like this:

    Code (csharp):
    1.  
    2. function Start(){
    3. player=gameObject.FindWithTag("Player")
    4. }
    5.  
     
  3. Airmand

    Airmand

    Joined:
    Jan 27, 2011
    Posts:
    139
    Ah, they are already in the scene when you start the game. I made sure to check that. While i was testing the game i made sure to check the inspector of each enemy and everything was correct.
     
  4. Airmand

    Airmand

    Joined:
    Jan 27, 2011
    Posts:
    139
    Ah ok. I changed the script and it works now. Thank you for the help.
    Code (csharp):
    1. var explosion : ParticleEmitter;
    2.  
    3.  
    4. function Update () {
    5. var player = gameObject.FindWithTag ("Player");
    6.     if(player) {
    7.         var dist = Vector3.Distance(player.transform.position, transform.position);
    8.         if(dist <= 4){
    9.             Destroy(gameObject);
    10.             PlayerHealth.playerhealth -= 4;
    11.             Instantiate(explosion, transform.position, transform.rotation);
    12.         }
    13.     }
    14. }
    15.  
    16.