0
\$\begingroup\$

In the spot //wait 1.5 seconds what would I say to make it wait 1.5 seconds then complete the code after?

Here is the code:

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

public class OnclickHeal : MonoBehaviour
{
    public PlayerHealth playerHealth;
    public PlayerMovement playerMovement;
    public Inventory Inventory;

    public Button healButton;

    void Start()
    {
        Button btn = healButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        playerMovement.moveSpeed = 3;
        //wait 1.5 seconds
        playerMovement.moveSpeed = 4;
        playerHealth.currentHealth = 100;
    }
}

Also, the line public Button healButton; throws an error:

error CS0246: The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)

\$\endgroup\$
1
  • \$\begingroup\$ When in doubt, be sure to search for your error message on StackOverflow. In this case, the compiler is complaining that you haven't told it where to find the Button type. It's in the UnityEngine.UI namespace, so where you have those using lines at the top of the file, you should add using UnityEngine.UI;. Your IDE should also suggest this fix if you hover over the line giving the error. \$\endgroup\$
    – DMGregory
    Nov 2, 2020 at 15:25

2 Answers 2

0
\$\begingroup\$

Use the Invoke() function to call a function after a certain delay

Invoke("DoSomething", 1.5);//this will happen after a delay of 1.5 seconds

Where DoSomething is the name of the function that can be defined arbitrarily

void DoSomething() {
  //do nothing
  return;
}

If you want to read up on more documentation and how you can make better use of them than my naive approach, you can search for Unity Invoke() and Invoke Co-routines(DoSomething is a co-routine in the above example).

\$\endgroup\$
0
1
\$\begingroup\$

This is what Coroutines are for. A coroutine allows you to execute a method with breaks while the rest of the game continues running.

When you have a series of actions which are supposed to be executed with breaks, move them into a method which returns an IEnumerator.

You can now use the construct yield return WaitForSeconds(1.5f); in that method to add breaks to this method.

In order for these breaks to work, you have to run it as a coroutine with the method StartCoroutine(MethodName()).

void TaskOnClick() {
    StartCoroutine(ChangeMoveSpeed());
}

private IEnumerator ChangeMoveSpeed() {
    playerMovement.moveSpeed = 3;
    yield return WaitForSeconds(1.5f);
    playerMovement.moveSpeed = 4;
    playerHealth.currentHealth = 100;
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .