Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 Human_Melon · Mar 29, 2020 at 03:44 PM · fpsenemyattack1st person

How do i make my enemy AI attack?

So i'm really new and i want that my Enemy would attack me and do a certain amount of damage (would be nice if there was a range and delay)

Here's my Enemy script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;

public class EnemyAII : MonoBehaviour {

 Transform playerTransform;
 UnityEngine.AI.NavMeshAgent myNavmesh;
 public float checkRate = 0.01f;
 float nextCheck;

 // Start is called before the first frame update
 void Start() {

     if (GameObject.FindGameObjectWithTag("Player").activeInHierarchy)
         playerTransform = GameObject.FindGameObjectWithTag("Player").transform;

     myNavmesh = gameObject.GetComponent<UnityEngine.AI.NavMeshAgent>();       
     }

 // Update is called once per frame
 void Update()
 {
     if (Time.time > nextCheck)
     {
         nextCheck = Time.time + checkRate;
         FollowPlayer();
     }
 }

 void FollowPlayer()
 {
     myNavmesh.transform.LookAt(playerTransform);
     myNavmesh.destination = playerTransform.position;
 }

}

And here's my playerHealth script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;

public class PlayerHealth : MonoBehaviour { public int maxHealth = 100; public int currentHealth;

 public HealthBar healthBar;

 // Start is called before the first frame update
 void Start()
 {
     currentHealth = maxHealth;
     healthBar.SetMaxHealth(maxHealth);
 }

 // Update is called once per frame
 void Update()
 {
     if // I don't know what to do here
     {
         TakeDamage(20);
     }
     if (currentHealth <= 0)
     {
         Die();
     }
 }    

 void Die()
 {
     SceneManager.LoadScene(SceneManager.GetActiveScene().name);
 }

 void TakeDamage(int damage)
 {
     currentHealth -= damage;

     healthBar.SetHealth(currentHealth);
 }

}

So basicly i want the enemy do damage until my health bar is at 0.

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
3
Best Answer

Answer by ahsen35813 · Mar 29, 2020 at 04:53 PM

My answer is completely untested, and might not be very good, but I think I have a solution To cause damage to the player, maybe you could use void OnTriggerEnter(Collider other){}to detect when the enemy makes contact with the player. Then you would need to add a trigger collider around the enemy for the enemy's attack range, so that the player will take damage when in that range. The script could be something like this:

 public class EnemyAttack : MonoBehaviour
 {
 
     public float enemyCooldown = 1;
     public float damage = 1;
 
     private bool playerInRange = false;
     private bool canAttack = true;
 
     private void Update()
     {
         if (playerInRange && canAttack)
         {
             GameObject.Find("Player").GetComponent<ControllerForPlayer>().currentHealth -= damage;
             StartCoroutine(AttackCooldown());
         }
     }
 
     void OnTriggerEnter(Collider other)
     {
         if (other.gameObject.CompareTag("Player"));
          {
             playerInRange = true;
         }
     }
     void OnTriggerExit(Collider other)
     {
         if (other.gameObject.CompareTag("Player"));
          {
             playerInRange = false;
         }
     }
     IEnumerator AttackCooldown()
     {
         canAttack = false;
         yield return new WaitForSeconds(enemyCooldown);
         canAttack = true;
     }
 }
 



Make sure to make the currentHealth variable in the player script public and everything else should work. IMPORTANT: DO NOT forget to add a trigger collider to the enemy to specify it's attack radius.

I really hope this works for you. Please let me know if it does! This was a really fun thing to try and figure out, so thanks for that.

EDIT: I've revised this code a couple of times now, and I can verify that it does indeed work for me, so hopefully it will work for you too.

Comment
Add comment · Show 5 · 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 Human_Melon · Mar 31, 2020 at 09:12 AM 0
Share

I get this error: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)

i'm trying to fix it.

avatar image Human_Melon · Mar 31, 2020 at 09:40 AM 0
Share

I change the float damage to int damage. The error is fixed, but i'm not taking damage

avatar image Human_Melon · Mar 31, 2020 at 09:47 AM 0
Share

I'm so sorry. I didn't attach the script to the enemy xD It works Thanks!!!!!

avatar image ahsen35813 · Apr 01, 2020 at 12:16 PM 0
Share

lol. I did the same thing when I was testing this. I forgot to attach the script to the enemy. I'm glad it works for you!

avatar image danimiroiu5 · Oct 18, 2021 at 08:59 AM 0
Share

what to write instead of ? cuz is giving me error on this line pls im really new

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

172 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

Related Questions

FPS , not attackking if the player behind ? 0 Answers

fps shooting enemy 1 Answer

Ai Alien Zombies get stuck on trees? 0 Answers

how do I edit enemy stats 3 Answers

Enemy follows player then attacks! 2 Answers


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