Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Follow player OnTriggerEnter

kinkehkinkeh Member
edited May 23 in Programming

Hi, I am making a small game for my school project. I have some patrolling ghosts in my scene, what i want to do is; I want the ghosts follow the player when the player is close to them and press E. here is my code so far.


using UnityEngine;
using UnityEngine.AI;

public class GhostCatch : MonoBehaviour
{
  GameObject player;
  NavMeshAgent ghost;
  bool touchIng = false;


  // Start is called before the first frame update
  void Start()
  {
    ghost = GetComponent<NavMeshAgent>();
    player = GameObject.FindGameObjectWithTag("Player");
  }

  // Update is called once per frame
  void Update()
  {
    if (touchIng && Input.GetKeyDown(KeyCode.E))
    {
      ghost.destination = player.transform.position;
    }
  }
  private void OnTriggerEnter(Collider other)
  {
    if (other.gameObject.tag == "Player")
    {
      touchIng = true;
    }
  }
  private void OnTriggerExit(Collider other)
  {
    if (other.gameObject.tag == "Player")
    {
      touchIng = false;
    }
  }
}

Answers

  • You could make an empty GameObject and move it to the position where you want the ghost to be when he is caught by the player. Then, Parent that Empty GameObject to the player. After that, You could Parent the ghost to that Empty GameObject and set the position on the x, y and z axis to zero using the Script when E is pressed or a Trigger is Triggered. And you are all set.

  • But if you want to make multiple ghost follow you, You will have to make multiple Empty GameObjects.

    The following should help:

    1. Set the Positions of the Empty GameObjects.

    2. Parent them to the player.

    3. In the script make an array of Transforms.

    4. Make a Transform Variable for the Ghost.

    5. Add the Empty GameObjects to the Array. Then, Run a foreach loop for each Transform in the Array you made for Transforms.

    Use: foreach (Transform <Any Name> in <Name of the Array>)

    {

    }


    Example:

    foreach(Transform example in ExampleArray)

    {

    if(example.childCount > 0)

    {

    // Parent the ghost to example

    ghost.setParent(example);

    }

    }

  • edited May 24

    Here's the code if you want (You can add this to your script):

    public Transform[] Example = new Transform[Integer value for the length];

    void OnTriggerEnter(Collider other)

    {

    if(other.CompareTag("Ghost"))

    {

    foreach(Transform others in Example)

    {

    if(others.childCount == 0)

    {

    other.SetParent(others.transform);

    }

    }

    }

    }

Sign In or Register to comment.