GetKeyDown P (Active a Script help)

I’m using this script that is (Free) Still learning C# code. But I want to active this script when the player presses P // if (Input.GetKeyDown(“P”))

Would you add something to this script or make a new script? If so any tutorials on how to do something like this or you able to help?

Thank you for your time.
Luke

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

public class WayPoints : MonoBehaviour
{
    // put the points from unity interface
    public Transform[] wayPointList;

    public int currentWayPoint = 0;
    Transform targetWayPoint;

    public float speed = 4f;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        // check if we have somewere to walk
        if (currentWayPoint < this.wayPointList.Length)
        {
            if (targetWayPoint == null)
                targetWayPoint = wayPointList[currentWayPoint];
            walk();
        }
    }

    void walk()
    {
        // rotate towards the target
        transform.forward = Vector3.RotateTowards(transform.forward, targetWayPoint.position - transform.position, speed * Time.deltaTime, 0.0f);

        // move towards the target
        transform.position = Vector3.MoveTowards(transform.position, targetWayPoint.position, speed * Time.deltaTime);

        if (transform.position == targetWayPoint.position)
        {
            currentWayPoint++;
            targetWayPoint = wayPointList[currentWayPoint];
        }
    }
}

You normally check for input in Update. But Update only gets called if the script component is already active. So check for input in another script which is active and with a reference to this script. You activate it from there. Something like below.

public WayPoints WayPointsComponent;    //Set this reference in the inspector

void Update()
{
    if ((Input.GetKeyDown(Keycode.P)) && (WayPointsComponent.enabled == false))
    {
        WayPointsComponent.enabled = true;
    }
}

Might be like this, added from Joe:

// Update is called once per frame
void Update()
{
    if ((Input.GetKeyDown(Keycode.P)) && (WayPointsComponent.enabled == false))
    {
        // check if we have somewere to walk
        if (currentWayPoint < this.wayPointList.Length)
        {
            if (targetWayPoint == null)
                targetWayPoint = wayPointList[currentWayPoint];
            walk();
        }
    }
}

You just need input in update.
Could you kindly elaborate your question. Because we don’t know the component(gameObject) is active or deactive.

Or there is a function that you can call when an entity get active or otherwise: That is:
void OnEnable()
{
}

1 Like