- Home /
Randomize which script is enabled
I would like for my class to randomly choose one script from an array of scripts and enable it.
Background: I have a Chase class for my monster, and within the class I reference to external movement scripts: a Jump and a Strafe. I don't want these movement scripts to fire at the same time, so I figure I should set up an array, and then randomly choose one to be enabled. Once the script is run, a bool turns it off and we go back to the Chase script to randomly choose another move. In this way, the moves are random and cycled.
Is it possible to store myScript.enabled = true; commands in an array? Is there a better way to randomly choose between turning on one of many scripts?
Answer by Koyemsi · May 05, 2018 at 02:19 PM
I think it would be better to have all these behaviors in a unique script. I would do something like this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomBehaviour : MonoBehaviour {
public enum EnemyBehaviour {
Sleeping,
Jumping,
Strafing
}
public EnemyBehaviour enemyWillBehave;
int enumCount;
float changeDelay = 1.0f;
void Start () {
enumCount = System.Enum.GetValues (typeof(EnemyBehaviour)).Length;
StartCoroutine (ChangeBehaviour ());
}
void Strafe () {
// strafing code
}
void Jump () {
// jumping code
}
IEnumerator ChangeBehaviour () {
enemyWillBehave = (EnemyBehaviour)Random.Range (0, enumCount);// randomize behaviour
print (enemyWillBehave);
switch (enemyWillBehave) {
case EnemyBehaviour.Sleeping:
// do whatever
break;
case EnemyBehaviour.Jumping:
Jump ();
break;
case EnemyBehaviour.Strafing:
Strafe ();
break;
}
yield return new WaitForSeconds (changeDelay);
StartCoroutine (ChangeBehaviour ());
}
}
Thanks much for taking the time to answer.
This involves changing my structure, but it looks so much more elegant.
I'll try to test it out some time this week and then get back with the results
You're welcome, glad if I could help. $$anonymous$$y solution might be one among others, as there are often several ways to solve a problem. Let me know how things go.
I've tried out an adapted version of the code above, and it's throwing a null reference exception: NullReferenceException UnityEngine.$$anonymous$$onoBehaviour.StartCoroutine (IEnumerator routine) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/$$anonymous$$onoBehaviourBindings.gen.cs:62)
I understand that null reference exception means that I'm asking the script to find/ use something that's not there. However, I don't understand what isn't there from this error message.
I didn't copy your script exactly. Since my Chase class is so long, I'll be keeping each move in a separate script. I moved the $$anonymous$$yScript.enabled = true command into the "Jump" and "Strafe" functions above.
I also took out the changeDelay and restart coroutine at the end, because I only want it to fire once.
Other than that, it's almost exactly the same. I hesitate to post the script because it's quite long, but I will try to give you some context:
Declarations:
private readonly NBStatePatternEnemy enemy;
private float chaseTimer;
public float jumpSpeed;
public float forwardSpeed;
public enum NB$$anonymous$$oves
{
Jumping,
Skittering
}
public NB$$anonymous$$oves nB$$anonymous$$oves;
int enumCount;
Getting the enum length:
public void Start()
{
enumCount = System.Enum.GetValues (typeof(NB$$anonymous$$oves)).Length;
}
Coroutine fires when the enemy sees the player at a certain distance:
RaycastHit hit;
if (Physics.Raycast(enemy.eyes.transform.position, enemy.eyes.transform.forward, out hit, enemy.sightRange) && hit.collider.CompareTag("Player") && hit.distance <= 18.0f)
StartCoroutine (Change$$anonymous$$ove ());
And here's the coroutine:
IEnumerator Change$$anonymous$$ove()
{
nB$$anonymous$$oves = (NB$$anonymous$$oves)Random.Range(0, enumCount);
print(nB$$anonymous$$oves);
switch (nB$$anonymous$$oves)
{
case NB$$anonymous$$oves.Jumping:
InitializeJump();
break;
case NB$$anonymous$$oves.Skittering:
InitializeSkitter();
break;
}
yield break;
}
you can't "yield break". Replace "StartCoroutine(Change$$anonymous$$ove());" with Change$$anonymous$$ove's body
Hi. I'm not sure of what's going on, but @iljuan is right, yield break is not good. I think you should replace this by yield return null;
No!! Don't do that! D:, IEnumerator doesn't work like that.
An IEnumerator is used to run Coroutines, which are basically virtual Threads ran in the same Thread. You use an IEnumerator when you want to execute something outside from your current stack, so that operation doesn't freezes your current process.
In Unity, "yield" should be always followed by "return new Wait..." (i.e, WaitUntilEndOfFrame(), WaitForSeconds(.1f), WaitFixedUpdate())
Anyways, given the case, you don't need a IEnumerator, there's no reason on using it. You were using it to create a Timer, now he isn't using that Timer anymore, so there's no reason at all to use that IEnumerator (what's even more, the code won't work with that IEnumerator there).
Just delete "Change$$anonymous$$ove()" method and copy it's content replacing "StartCoroutine (Change$$anonymous$$ove ());"
Thanks, all.
If I may sum up the lessons for anyone who finds this page:
You can randomize a SWITCH command if you want to have your script choose other scripts to enable/disable randomly.
That SWITCH command can be in a regular old function, or in a coroutine if you need it to repeat on a timer.
The way to get out of a switch without a WaitForSeconds call is simply
yield return null;
.
Sum$$anonymous$$g up for the other users is a really nice intention.
But I think your summary has incorrect points (especially the 3rd one) which need to be corrected or reformulated.
You don't "get out of a switch()
". You could say at most that you get out of the case
statements within the switch (and this is done with a break
instruction).
You probably meant that yield return null
was a way to get out of a IEnumerator
(a coroutine) ; this is better, even if I'm not sure this is the exact way to understand the yield concept.
Anyway, let's retain that this works ;)