Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by rsulkosky · May 05, 2018 at 09:37 AM · arraymovement scriptcomponentrandomizestructure

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?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

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 ());
     }
 }
 
Comment
Add comment · Show 11 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rsulkosky · May 05, 2018 at 11:41 PM 0
Share

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

avatar image Koyemsi rsulkosky · May 06, 2018 at 09:45 AM 0
Share

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.

avatar image rsulkosky · May 12, 2018 at 01:44 AM 0
Share

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;
     }


avatar image iJuan rsulkosky · May 12, 2018 at 01:53 AM 0
Share

you can't "yield break". Replace "StartCoroutine(Change$$anonymous$$ove());" with Change$$anonymous$$ove's body

avatar image Koyemsi rsulkosky · May 12, 2018 at 02:39 AM 0
Share

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;

avatar image iJuan Koyemsi · May 12, 2018 at 02:52 AM 0
Share

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 ());"

Show more comments
avatar image rsulkosky · May 13, 2018 at 07:05 AM -1
Share

Thanks, all.

If I may sum up the lessons for anyone who finds this page:

  1. You can randomize a SWITCH command if you want to have your script choose other scripts to enable/disable randomly.

  2. That SWITCH command can be in a regular old function, or in a coroutine if you need it to repeat on a timer.

  3. The way to get out of a switch without a WaitForSeconds call is simply yield return null;.

avatar image Koyemsi rsulkosky · May 13, 2018 at 03:21 PM 0
Share

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 ;)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

98 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Array variables structure question 1 Answer

Randomly remove list values 1 Answer

Question (or recommendation) on my data structure for getting Prefabs into an array (as gameobjects?) 0 Answers

Change color of all buttons listed in array 3 Answers

Why can't i use these arrays to access positions and objects properties? Please help! 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges