need help for adding a delay code before walking of npc
Hi,
I don't know much about C# coding, and been trying to make a project for university using codes from all over the web. right now i'm stuck because can't find a code to allow the npc that walks, wait for a set amount of time before it starts walking. so was wondering if anyone can help with the code to add a delay before executing the walk.
Thanks in advance
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walking : MonoBehaviour
{
public float movespeed;
private Rigidbody myRigidbody;
public bool isWalking;
public float walkTime;
private float walkCounter;
public float waitTime;
private float waitCounter;
private int WalkDirection;
// Start is called before the first frame update
void Start()
{
Invoke("DoSomething", 2);
myRigidbody = GetComponent<Rigidbody>() ;
waitCounter = waitTime;
walkCounter = walkTime;
ChooseDirection() ;
}
// Update is called once per frame
void Update()
{
switch(WalkDirection)
{
case 0:
myRigidbody.velocity = new Vector2(movespeed, 0) ;
break;
}
if(isWalking)
{
walkCounter -= Time.deltaTime;
if(walkCounter < 0)
{
isWalking = false;
waitCounter = waitTime;
}
}
else
{
waitCounter -= Time.deltaTime;
myRigidbody.velocity = Vector2.zero;
if(waitCounter < 0)
{
ChooseDirection();
}
}
}
public void ChooseDirection ()
{
WalkDirection = Random.Range (0, 1);
isWalking = true;
walkCounter = walkTime;
}
}
Answer by Dsiak · Nov 21, 2021 at 08:35 AM
You are going to need a Coroutine, that is a code that runs parallel to the rest of your code. You can try something like this:
private void Start()
{
StartCoroutine(WalkCoroutine());
}
IEnumerator WalkCoroutine()
{
while (true)
{
StartWalk();
yield return new WaitForSeconds(waitTime);
StopWalk();
}
}
void StartWalk()
{
//Implement Walking
}
void StopWalk()
{
//Implement Stop Walking
}
Answer by unity_hosein · Nov 22, 2021 at 03:51 AM
when you use return you are exiting. use this code : private void Update() { StartCoroutine(WalkCoroutine()); } void WalkCoroutine() { while (true) { StartWalk(); Wait(); StopWalk(); } } IEnumerator Wait() { yield return new WaitForSeconds(waitTime); } void StartWalk() { //Implement Walking } void StopWalk() { //Implement Stop Walking }
Your answer
Follow this Question
Related Questions
Wait time Before Camera Switching? 0 Answers
How to wait a certain amount of seconds in C# 4 Answers
c# shooting problem (probably pretty simple) 2 Answers
Show ad after certain line of code is called 5 times 1 Answer
IENumerator does not work 0 Answers