• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by MortalTom · Oct 15, 2016 at 06:20 AM · scripting beginnerinstancesautomate

Instanced enemies not interacting correctly with player

I am trying to make a system of automatic attacks that happen when enemies are in contact with a player object, I have my enemies populate a list when they enter the players trigger and then on my players auto attack I have a for loop that (I hope) is cycling through each enemy in the list and dealing damage to them. This all works fine if there is only one instance of my enemy prefab, when a second is added the player only begins to run its attack function when the original instanced enemy enters its trigger, however it only affects the health of the last enemy instanced. All instances of my enemy correctly damage the player. I am wondering what it is I am doing wrong and if anyone can help me it would be greatly appreciated as I have been stuck on this for a few days now.

I do not know where the problem is coming from so will copy all three of my scripts, thank you in advance to anyone who sifts through the whole thing

edit:- I have noticed that all of my instanced enemies are being added to the list at once, despite the intent of adding them one at a time when they collide. So I think the problem is likely coming from the way I am adding them, and the instanced scripts are not being referenced just the prefab script

My player script:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class Player : MonoBehaviour {
 
     public int attack;
     public int defense;
     public int health;
     public Text playerHealthText;
     public GameObject enemy;
     public GameObject combatManager;
     public float attackSpeed;
 
     private BoxCollider2D enemyTrigger;
     private CombatManager combatManagerScript;
     private bool enemyDetected;
     public float attackTimer;
 
 
     // Use this for initialization
     void Start () {
 
         enemy = GameObject.Find ("Enemy");
         combatManager = GameObject.Find ("CombatManager");
         playerHealthText = GameObject.Find ("PlayerHealthDisplay").GetComponent<Text> ();
         playerHealthText.text = "" + health;
         enemyTrigger = enemy.GetComponent<BoxCollider2D> ();
         combatManagerScript = combatManager.GetComponent<CombatManager> ();
         enemyDetected = false;
         attackTimer = attackSpeed;
     
     }
 
     void interactWithEnemy()
     {
         combatManagerScript.playerAttackAction ();
     }
 
     void OnTriggerStay2D (Collider2D other)
     {
         if (other == enemyTrigger)
         {
             enemyDetected = true;
         }
     }
 
     void OnTriggerEnter2D (Collider2D other)
     {
         if (other == enemyTrigger)
         {
             interactWithEnemy ();
         }
     }
     
     // Update is called once per frame
     void Update () {
 
         if (enemyDetected == true)
         {
             if (attackTimer >= 0)
             {
                 attackTimer -= Time.deltaTime;
             }
             else
             {
                 interactWithEnemy ();
                 attackTimer = attackSpeed;
             }
         }
     }
 }


My enemy script:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class Enemy : MonoBehaviour {
 
     public int attack;
     public int defense;
     public int health;
     public Text enemyHealthText;
     public GameObject combatManager;
     public GameObject player;
     public GameObject gameManager;
     // speed variable controls both the speed and direction of the moving object a positive number moves left a negative number moves right
     public float speed;
     public float attackSpeed;
     public bool playerDetected;
 
     public GameObject currentEnemy;
     private BoxCollider2D playerTrigger;
     private BoxCollider2D gameSpace;
     private CombatManager combatManagerScript;
     private SpriteRenderer facing;
     private float attackTimer;
 
 
 
     // Use this for initialization
     void Start () {
 
         currentEnemy = this.gameObject;
         combatManager = GameObject.Find ("CombatManager");
         player = GameObject.Find ("Player");
         gameManager = GameObject.Find ("GameManager");
         enemyHealthText = currentEnemy.GetComponentInChildren<Text>();
         enemyHealthText.text = "" + health;
         combatManagerScript = combatManager.GetComponent<CombatManager> ();
         playerTrigger = player.GetComponent<BoxCollider2D> ();
         gameSpace = gameManager.GetComponent<BoxCollider2D> ();
         facing = GetComponent<SpriteRenderer> ();
         playerDetected = false;
         attackTimer = attackSpeed;
     
     }
 
     void moveEnemy()
     {
         if (playerDetected == false)
         {
             // moves the attached object left across the screen
             transform.Translate (new Vector3 (-1f, 0f, 0f) * speed * Time.deltaTime);
         }
     }
 
     void interactWithPlayer()
     {
         combatManagerScript.enemyAttackAction ();
     }
 
     void OnTriggerStay2D (Collider2D other)
     {
         if (other == playerTrigger)
         {
             playerDetected = true;
         }
     }
 
     void OnTriggerExit2D(Collider2D other)
     {
         if (other == gameSpace)
         {
             speed = -speed;
             if (facing.flipX == true) {
                 facing.flipX = false;
             }
             else
             {
                 facing.flipX = true;
             }
         }
     }
 
     void OnTriggerEnter2D (Collider2D other)
     {
         if (other == playerTrigger) 
         {
             interactWithPlayer ();
             combatManagerScript.addToList ();
         }
     }
     
     // Update is called once per frame
     void Update () {
 
         moveEnemy ();
         if (playerDetected && !player)
         {
             playerDetected = false;
         }
 
         if (playerDetected == true)
         {
             if (attackTimer >= 0) 
             {
                 attackTimer -= Time.deltaTime;
             }
             else 
             {
                 interactWithPlayer ();
                 attackTimer = attackSpeed;
             }
         }
     }
 }

and finally my combat manager:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine.UI;
 
 public class CombatManager : MonoBehaviour {
 
 
     public GameObject player;
     public GameObject enemy;
     public bool playerTurn;
     public List<Enemy> enemies;
 
     private Player playerScript;
     private Enemy enemyScript;
 
 
     // Use this for initialization
     void Awake () {
 
         player = GameObject.Find ("Player");
         enemy = GameObject.FindWithTag ("Enemy");
         enemies = new List<Enemy>();
         playerScript = player.GetComponent<Player>();
         enemyScript = enemy.GetComponent<Enemy> ();
         playerTurn = true;
 
     }
 
     //the players automatic attack
     public void playerAttackAction ()
     {
         int damage = playerScript.attack - enemyScript.defense;
         int i;
 
         if (damage <= 0) {
             return;
         } 
         for (i = 0; i < enemies.Count; i++)
         {
             enemies[i].health = enemies[i].health - damage;
             enemies[i].enemyHealthText.text = "" + enemies[i].health;
         }
     }
 
 
     public void enemyAttackAction ()
     {
         int damage = enemyScript.attack - playerScript.defense;
 
         if (damage <= 0) {
             return;
         }
         playerScript.health = playerScript.health - damage;
         playerHealthUpdate ();
     }
 
     public void addToList()
     {
         enemies.Add (enemy.GetComponent<Enemy> ());
     }
 
 
     private void playerHealthUpdate()
     {
         playerScript.playerHealthText.text = "" + playerScript.health;
     }
     
     // Update is called once per frame
     void Update () {
 
         if (enemyScript.health <= 0) {
             Destroy (enemy);
         }
 
         if (playerScript.health <= 0) {
             Destroy (player);
         }
     }
 }

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by OusedGames · Oct 15, 2016 at 04:34 PM

I found your error:

You'are adding only one enemy to the list

  • Script Combat Manager

  • Function addToList

You are ading the enemy you get at Awake to the List

  • enemy = GameObject.FindWithTag ("Enemy");

  • That is why you are taking damage from only one Enemy


You should:

  • In your enemy script

  • When enemy collided with player

  • You add the enemy to the list

  • void OnTriggerEnter2D (Collider2D other) { if (other.gameObject.tag == "Player"){ CombatManager.addToList(this.gameObject);


  • You need to add every enemy to the list, not Find one; Because you need to get every instance

  • @MortalTom

Good Lucky Buddy

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MortalTom · Oct 15, 2016 at 05:23 PM 0
Share

Thank you so much, it was driving me nuts!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Problems with Gyroscope VR Car Game 0 Answers

Deforming a cylinder when pressed by my hand. 2 Answers

Is there a way to recapitulate this? 1 Answer

Linking Image to item list 1 Answer

How can I share code between simple intractable objects in a first person game. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges