Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 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
2
Question by Persoc · Apr 02, 2015 at 01:33 PM · scripting problemtriggerenemy ai

Basic Enemy AI in C#

Hello, I'm new to scripting in Unity and have been trying to script a basic enemy AI for my project. The idea is there is a trigger that the EnemyTerritory script is attached to and an enemy object the BasicEnemy is attached to. The plan is that when the player enters the trigger the territory script will tell it's attached enemy to move towards the player, and a separate script will allow it to attack. If the player leaves the territory it will enter a rest state and do nothing. My two problems with this are that when I start the game the enemy makes a beeline for my player, even though the player is nowhere near the territory. The second is that the enemy is not restricted to only moving on the X axis, even though I have a rigidbody attached with Y and Z frozen. Any help would be greatly appreciated!

 public class EnemyTerritory : MonoBehaviour
 {
         public BoxCollider territory;
         GameObject player;
         bool playerInTerritory;
 
         public GameObject enemy;
         BasicEnemy basicenemy;
 
         // Use this for initialization
         void Start ()
         {
             player = GameObject.FindGameObjectWithTag ("Player");
             basicenemy = enemy.GetComponent <BasicEnemy> ();
             playerInTerritory = false;
         }
     
         // Update is called once per frame
         void Update ()
         {
             if (playerInTerritory = true)
             {
                 basicenemy.MoveToPlayer ();
             }
 
             if (playerInTerritory = false)
             {
                 basicenemy.Rest ();
             }
         }
 
         void OnTriggerEnter (Collider other)
         {
             if (other.gameObject == player)
             {
                 playerInTerritory = true;
             }
         }
     
         void OnTriggerExit (Collider other)
         {
             if (other.gameObject == player) 
             {
                     playerInTerritory = false;
             }
         }
 }
 
 public class BasicEnemy : MonoBehaviour
 {
         public Transform target;
         public float speed = 3f;
         public float attack1Range = 1f;
         public int attack1Damage = 1;
         public float timeBetweenAttacks;
 
 
         // Use this for initialization
         void Start ()
         {
             Rest ();
         }
     
         // Update is called once per frame
         void Update ()
         {
             
         }
 
         public void MoveToPlayer ()
         {
             //rotate to look at player
             transform.LookAt (target.position);
             transform.Rotate (new Vector3 (0, -90, 0), Space.Self);
         
             //move towards player
             if (Vector3.Distance (transform.position, target.position) > attack1Range) 
             {
                     transform.Translate (new Vector3 (speed * Time.deltaTime, 0, 0));
             }
         }
 
         public void Rest ()
         {
 
         }
 }
 
 
Comment
Add comment · Show 2
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 Nobel_Seven · Mar 21, 2017 at 02:57 PM 0
Share

can you please make a basic enemy attack script.

avatar image DeveshPandey · Mar 26, 2018 at 05:08 PM 0
Share

Here is a good plugin, it may help you.

https://www.assetstore.unity3d.com/#!/content/87744?aid=1101l34jr

3 Replies

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

Answer by blueteak · Apr 02, 2015 at 01:52 PM

 if (playerInTerritory = true)
 {
      basicenemy.MoveToPlayer ();
 }

should be

 if (playerInTerritory == true)
 {
       basicenemy.MoveToPlayer ();
 }


You are setting playerInTerritory to true there.

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 Persoc · Apr 02, 2015 at 06:39 PM 0
Share

Can't believe I missed that, It works! Thank you!

avatar image blueteak · Apr 02, 2015 at 09:01 PM 0
Share

$$anonymous$$ake sure to mark answers as correct so people know that it's solved.

avatar image
0

Answer by sunil1 · Mar 21, 2017 at 06:01 AM

using System.Collections; using System.Collections.Generic;

using UnityEngine.UI; using UnityEngine;

public class AiofFatZombies : MonoBehaviour { Transform player; public Animator anim; public float playerHealth = 100; public Text playerhath; UnityEngine.AI.NavMeshAgent nav; public Texture blooody; public bool allowtohit=false; float navspeed=0.5f; public static float floathealth= 100; public bool zombiesdeath = false;

  void Awake()
 {
     if (!zombiesdeath)
     {
         nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
         //  player = GameObject.FindGameObjectWithTag("Player").transform;
         player = GameObject.FindGameObjectWithTag("Player").transform;
         anim = GetComponent<Animator>();

         playerhath.text = "Player Health =" + floathealth.ToString();

     }

 }
  void OnGUI()
 { 
     nav.SetDestination(player.position);
     float distance = Vector3.Distance(player.transform.position, this.transform.position);
    
         navspeed += Time.deltaTime/50;

         nav.speed = navspeed;



         anim.SetBool("walk", true);
         anim.SetBool("attack",false);

         if (distance <=7)
         {
         nav.Stop();

             anim.SetBool("attack", true);
    floathealth -= Time.deltaTime;
         playerhath.text = "Player Health=  " +floathealth.ToString();
         if((int)floathealth==0)
         {
             hero.sendmassage = 1;


         }

         GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), blooody);
   
             anim.SetBool("walk", false);
             
         
         }
    
         
     }
  
 
  public void ApplyDamage(float damage)

 {
     playerHealth -= damage;
     if(playerHealth==0)
     {
     
         Death();

     }

 }
  public void Death()
 {
     zombiesdeath = true;
     nav.Stop();
     anim.SetTrigger("death");
     Destroy(this.gameObject, 10.0f);
 }

   
 


}

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 Nobel_Seven · Mar 21, 2017 at 02:57 PM 0
Share

can you be more clear.

avatar image moneyman4720 · Nov 19, 2020 at 05:23 PM 0
Share

void Awake() { if (!zombiesdeath) { nav = GetComponent (); // player = GameObject.FindGameObjectWithTag("Player").transform; player = GameObject.FindGameObjectWithTag("Player").transform; anim = GetComponent(); playerhath.text = "Player Health =" + floathealth.ToString(); } } void OnGUI() { nav.SetDestination(player.position); float distance = Vector3.Distance(player.transform.position, this.transform.position);

      navspeed += Time.deltaTime/50;
      nav.speed = navspeed;
      anim.SetBool("walk", true);
      anim.SetBool("attack",false);
      if (distance <=7)
      {
      nav.Stop();
          anim.SetBool("attack", true);
 floathealth -= Time.deltaTime;
      playerhath.text = "Player Health=  " +floathealth.ToString();
      if((int)floathealth==0)
      {
          hero.sendmassage = 1;
      }
      GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), blooody);
   
          anim.SetBool("walk", false);
          
      
      }
 
      
  }
  
 

public void ApplyDamage(float damage) { playerHealth -= damage; if(playerHealth==0) {

      Death();
  }

} public void Death() { zombiesdeath = true; nav.Stop(); anim.SetTrigger("death"); Destroy(this.gameObject, 10.0f); }

avatar image
0

Answer by mei2011 · Jan 20, 2021 at 05:31 PM

what do I attach this to

Comment
Add comment · 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

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

10 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

Related Questions

Animator Trigger Not Working 1 Answer

2D Platformer - Picking Up Items & Storing Them C# 0 Answers

What is the best way to update array in runtime? 3 Answers

Play animation of FPS player after hitting trigger 2 Answers

OnTriggerEnter causing lag spike? 0 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