- Home /
How to make a character randomly select the action per time unit?
I am trying to make my character choose whether stand or walk each time unit randomly with higher possibility for walking. I tried to make a separate coroutine for this which i called RandomWalk, however when I play this my character never stands and the play mode stops all the time
public class WalkScript : MonoBehaviour {
Animator anim;
float Sprint;
float v;
bool hitFlag = false;
public List<int> turnPossibilities = new List<int>();
private Quaternion startingRotation;
public float speed = 10f;
IEnumerator Walk()
{
yield return new WaitForSeconds(0f);
Walking();
}
IEnumerator Stand()
{
yield return new WaitForSeconds(0f);
Standing();
}
IEnumerator RandomMove(float waitTime)
{
while (true)
{
yield return new WaitForSeconds(waitTime);
Choose();
}
}
void Start()
{
anim = GetComponent<Animator>();
startingRotation = this.transform.rotation;
StartCoroutine("RandomMove");
}
void Walking()
{
v = 0.2f;
anim.SetFloat("Walk", v);
}
void Standing()
{
v = 0f;
anim.SetFloat("Walk", v);
}
void Choose()
{
var number = Random.value;
if (number < 0.8f)
StartCoroutine("Walk");
else StartCoroutine("Stand");
}
}
Answer by mansoor090 · Dec 04, 2018 at 11:43 AM
Your Coroutine parameter is wrong in the start function
StartCoroutine(RandomMove(Floatvalue?));
And Start Coroutine doesnt repeat itself. try to use
InvokeRepeating ("Choose", 1f, 1f);
the first 1f represents starting delay and the next 1f is the delay for repeating. and do not forget to stop coroutine when next coroutine is called.
Fixing the parameter helped, thanks. But why do I need to call invokeRepeating for choose if it keeps calling choose in a while loop?
you can have time control on your task using invokerepeating. where as in while loop there will be numbers of calls at a time. i will recommened you to try the difference
Your answer
![](https://koobas.hobune.stream/wayback/20220612183316im_/https://answers.unity.com/themes/thub/images/avi.jpg)