0

How can I have my enemy disable a script once it reaches target player? I want to reference this script called casting under my GameManager in my code and disable it but I'm unsure how to write the function for when target location is reached.

public float lookRadius = 40f;

Transform target;
UnityEngine.AI.NavMeshAgent agent;

Rigidbody theRigidBody;

void Start()
{
    target = PlayerManager.instance.player.transform;
    agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
}

void Update()
{
    float distance = Vector3.Distance (target.position, transform.position);
    if (distance <= lookRadius)
    {
        agent.SetDestination (target.position);

        if (distance <= agent.stoppingDistance)
        {
            FaceTarget ();
        }
    }
}

void FaceTarget()
{
    Vector3 direction = (target.position - transform.position).normalized;
    Quaternion lookRotation = Quaternion.LookRotation (new Vector3 (direction.x, 0, direction.z));
    transform.rotation = Quaternion.Slerp (transform.rotation, lookRotation, Time.deltaTime * 5f);
}


// Use this for initialization
public void OnObjectSpawn ()
{
    //myRender = GetComponent<Renderer> ();
    theRigidBody = GetComponent<Rigidbody>();
}

void OnDrawGizmosSelected()
{
    Gizmos.color = Color.red;
    Gizmos.DrawWireSphere (transform.position, lookRadius);
}
Alex Myers
  • 6,196
  • 7
  • 23
  • 39

1 Answers1

0

You need to obtain the gameobject that has the script, get the script on that gameobject, and disable.

if (distance < 1f) // or some distance
{
    Gameobject mygo = GameObject.Find("GameManager"); // or some other method to get gameobject.
    mygo.GetComponent<casting>().enabled = false;
}
ryeMoss
  • 4,303
  • 1
  • 15
  • 34
  • Thanks. Also, how will I detect when target is reached? do I add a function called `public void TargetReached()`? –  Apr 11 '18 at 22:32
  • you already have the `distance` between the transform and your target. pick a value for how close you need to be. – ryeMoss Apr 11 '18 at 22:46