Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 dariusneag04 · Nov 18, 2021 at 04:39 PM · 2dscript.enemyattackingenemy damage

Make enemy damage the player,Enemy do damage to player Script

So i'm working on my first 2D game and I've made my character to do damage to the enemy , but I can't make the enemy to damage my character. Here's the script for my character combat:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityStandardAssets.CrossPlatformInput;
 
 public class PlayerCombat : MonoBehaviour
 {
     public Animator animator;
     public Transform attackPoint;
     public float attackRange = 0.5f;
     public LayerMask enemyLayers;
    
     AudioSource m_swingSound;
     
     
 
     public int attackDamage = 40;
     public float attackRate = 2f;
     float nextAttackTime = 0f;
     void Start()
     {
         m_swingSound = GetComponent<AudioSource>();
     }
     private void Update()
     {
         if (Time.time >= nextAttackTime)
         {
             if (CrossPlatformInputManager.GetButtonDown("Attack"))
             {
                
                 Attack();
                 m_swingSound.Play();
                 nextAttackTime = Time.time + 2f / attackRate;
             }
         }
 
 
     }
 
     void Attack()
     {
         animator.SetTrigger("Attack");
         //Detect enemies in range of attack
         Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
         //Damage them
         foreach (Collider2D enemy in hitEnemies)
         {
             enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
             
             
 
         }
     }
 
     void OnDrawGizmosSelected()
     {
         if (attackPoint == null)
             return;
         Gizmos.DrawWireSphere(attackPoint.position, attackRange);
     }
 }

Here's my character health script:

 sing System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 
 public class PlayerHealth : MonoBehaviour
 {
     public int maxHealth = 50;
     public int currentHealth;
     public HealthBar healthBar;
 
     void Start()
     {
         currentHealth = maxHealth;
         healthBar.SetMaxHealth(maxHealth);
         
     }
 }

Here's the enemy attack script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Enemy : MonoBehaviour
 {
     public Animator animator;
     public int maxHealth = 100;
     int currentHealth;
     public Enemy_Behaviour enemyBehaviour;
     [SerializeField] public GameObject gameObject;
     [SerializeField] public AudioSource audioSource;
     
 
     void Start()
     {
         currentHealth = maxHealth;
     }
 
     public void TakeDamage(int damage)
     {
         currentHealth -= damage;
         animator.SetBool("Attack", true);
         animator.SetTrigger("Hurt");
         if(currentHealth <= 0)
         {
             Die();
             
         }
     }
     
     void Die()
     {
         animator.SetBool("isDead", true);
         audioSource.Play();
         GetComponent<Collider2D>().enabled = false;
         this.enabled = false;
         enemyBehaviour.enabled = false;
         
         Destroy(gameObject, 2f);
 
 
 
 
 
     }
     
 }
 

And here's enemy's behaviour script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Enemy_Behaviour : MonoBehaviour
 {
     #region Public Variables
     
     
     
     public float attackDistance; //Minimum distance
     public float moveSpeed;
     public float timer; //Cooldown of attacks
     public Transform leftLimit;
     public Transform rightLimit;
     [HideInInspector] public Transform target;
     [HideInInspector] public bool inRange; //See if player in range
     public GameObject hotZone;
     public GameObject triggerArea;
     #endregion
 
     #region Private Variables
 
 
     private Animator animator;
     private float distance; //store distance between enemy and player
     private bool attackMode;
     
     private bool cooling; //check if enemy is cooling after attack
     private float intTimer;
     #endregion 
 
     void Awake()
     {
         SelectTarget();
         intTimer = timer;
         animator = GetComponent<Animator>();
     }
 
     // Update is called once per frame
     void Update()
     {
         if (!attackMode)
         {
             Move();
         }
 
         if(!InsideofLimits() && !inRange && !animator.GetCurrentAnimatorStateInfo(0).IsName("Enemy_attack"))
         {
             SelectTarget();
         }
 
         if (inRange)
         {
 
             EnemyLogic();
         }
     }
 
   
 
     void EnemyLogic()
     {
         distance = Vector2.Distance(transform.position, target.position);
 
         if (distance > attackDistance)
         {
             StopAttack();
         }
         else if (attackDistance >= distance && cooling == false)
         {
             Attack();
         }
 
         if (cooling)
         {
             Cooldown();
             animator.SetBool("Attack", false);
         }
     }
 
     void Move()
     {
         animator.SetBool("canWalk", true);
 
         if (!animator.GetCurrentAnimatorStateInfo(0).IsName("enemy1Attack"))
         {
             Vector2 targetPosition = new Vector2(target.position.x, transform.position.y);
 
             transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
 
         }
     }
 
     void Attack()
     {
         timer = intTimer;
         attackMode = true;
         animator.SetBool("canWalk", false);
         animator.SetBool("Attack", true);
     }
 
     void Cooldown()
     {
         timer -= Time.deltaTime;
 
         if (timer <= 0 && cooling && attackMode)
         {
             cooling = false;
             timer = intTimer;
         }
     }
 
     void StopAttack()
     {
         cooling = false;
         attackMode = false;
         animator.SetBool("Attack", false);
     }
 
     
 
     public void TriggerCooling()
     {
         cooling = true;
     }
 
     private bool InsideofLimits()
     {
         return transform.position.x > leftLimit.position.x && transform.position.x < rightLimit.position.x;
     }
     
     public void SelectTarget()
     {
         float distanceToLeft = Vector2.Distance(transform.position, leftLimit.position);
         float distanceToRight = Vector2.Distance(transform.position, rightLimit.position);
 
         if(distanceToLeft > distanceToRight)
         {
             target = leftLimit;
         }
         else
         {
             target = rightLimit;
         }
 
         Flip();
     }
 
     public void Flip()
     {
         Vector3 rotation = transform.eulerAngles;
         if(transform.position.x > target.position.x)
         {
             rotation.y = 180f;
         }
         else
         {
             rotation.y = 0f;
         }
 
         transform.eulerAngles = rotation;
     }
 }

I would tremendously appreciate the help

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
0

Answer by Bmarlyman21 · Nov 20, 2021 at 06:44 PM

I noticed on your Enemy script you have a method called "TakeDamage" which allows the player to damage the enemy. You don't appear to have the same thing on your "PlayerHealth" script. Also in your "Enemy_Behavior" script, you seem to only have functionality for animation in the "Attack" method, and nothing to do with affecting the player's health.

I would add 2 things:

1) Add a method on your PlayerHealth script which subtracts damage from health, just like you have in your Enemy script.

2) Get a reference to PlayerHealth in your Enemy_Behavior script, then call the damage method you've just created.

Let me know if that helps.

Comment
Add comment · Show 2 · 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 dariusneag04 · Nov 23, 2021 at 07:55 PM 0
Share

Yep, that worked perfectly, thank a lot!

avatar image Bmarlyman21 dariusneag04 · Nov 23, 2021 at 10:20 PM 0
Share

No problem, glad I could help! If this was the answer you were looking for, consider marking it as the accepted answer for this post.

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.

Follow this Question

Answers Answers and Comments

322 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

SetDestination function error 0 Answers

clones dying at the same time. why? 1 Answer

3d Buzz 2D tutorial - CharacterController2D - Enemies. 1 Answer

Instantiate GameObject on GUI Button click and rotate the object. 1 Answer

Object: collider to floor, trigger to player 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