Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

enemy detection in 2d

Discussion in '2D' started by ElegantUniverse, Oct 5, 2018.

  1. ElegantUniverse

    ElegantUniverse

    Joined:
    Sep 13, 2018
    Posts:
    78
    hello all
    I want to enemies follow my player in 2d ,I used this code but i dont know why enemy doesnt do anything?
    Code (CSharp):
    1.  
    2. public class Enemy : MonoBehaviour
    3. {
    4.     Rigidbody2D rg;
    5.     Animator anim;
    6.     float dirx, walkspeed = 5f;
    7.     bool isHurting, isDead;
    8.  
    9.     public float speed;
    10.     private Transform target;
    11.  
    12.     void start() {
    13.     target=GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    14.     rg = GetComponent<Rigidbody2D>();
    15.     anim = GetComponent<Animator>();
    16.     }
    17.  
    18.     void Update()
    19.     {
    20.  
    21.  
    22.  
    23.             transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    24.  
    25.  
    26.             dirx = Input.GetAxisRaw("Horizontal") * walkspeed;
    27.  
    28.             anim.SetBool("isWalking", true);
    29.     }
    30.  
    31. }
     
    Last edited: Oct 5, 2018
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Well "it doesn't work" does not tell me much, but I'll take a shot in the dark and say you are probably getting a null reference exception on your
    target
    reference, because you are attempting to supply the reference using
    FindGameObjectWithTag
    .

    For this to work, make sure there is only one GameObject in your scene with a tag exactly named like "Player".
     
    ElegantUniverse likes this.
  3. ElegantUniverse

    ElegantUniverse

    Joined:
    Sep 13, 2018
    Posts:
    78
    I mean i wrote this code then I drag its script to my enemy's object , when i run unity for test, enemy doesn't do any thing.
    I checked what you said , there is only one game object with "Player" tag

    by the way i have this error:
    NullReferenceException: Object reference not set to an instance of an object
    Enemy.Update () (at Assets/scripts/Enemy/Enemy.cs:25)
    for this line:
    Code (CSharp):
    1.  transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
     
    Last edited: Oct 5, 2018