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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Is there another way to have an Enemy GameObject chase the Player?

Discussion in 'Scripting' started by macfrelix, Apr 7, 2023.

  1. macfrelix

    macfrelix

    Joined:
    Mar 31, 2020
    Posts:
    4
    Im trying to figure out if there is another way the have an Enemy GameObject Chase and follow the Player without needing to having to using "public Transform", or for a way that the game automatically places the Player Object into the enemy script, or anything like the two examples. Is this possible or am I sol? I could really use the help, thank you.

    image_2023-04-06_233218258.png
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,455
    You can use find with tag to find the player, use singleton, static player reference, initialization with a reference from a manager class.
    For movement navmesh also is good
     
  3. macfrelix

    macfrelix

    Joined:
    Mar 31, 2020
    Posts:
    4
    Thank you, ill definitely try that.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,949
  5. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    717
    You need to separate your problems out!

    You're thinking of it like this:
    • I need another way to chase the player without having to set the player's transform manually in advance
    But it's really two problems:
    • I need a way to make the enemy chase something
    • I need a way to tell the enemy about the player
    A few reasonable solutions for problem 2 here:
    • Use a tag to identify the player
    • Use a specific component to identify the player, and search the scene for that component
    • Have a singleton game controller that the player registers themselves with, then have the enemies ask the manager about the player
     
    macfrelix and Kurt-Dekker like this.
  6. macfrelix

    macfrelix

    Joined:
    Mar 31, 2020
    Posts:
    4
    Oh, I'm sorry, I didn't know. This is my first time posting. Thank you for your input on what is the proper way to post code. I'll keep that in mind for the future.
     
  7. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    ML Agents
     
  8. macfrelix

    macfrelix

    Joined:
    Mar 31, 2020
    Posts:
    4
    Hmm, I've never thought about it that way. Thank you for your help, Ill definitely try to figure out with that in mind.