Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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 Kody Birchfield · Jul 14, 2015 at 12:38 PM · c#efficiencylearning

More efficient Scripting.

Hello, I'm still learning C#, and I ran into whats not really a problem, but what I feel can be heavily improved upon.

  1. The objectClock clock will not be counting in 5s, that's just for a test as the, but I still feel it could be improved. I will be adding more objects to the objectClock and change the clock variable to call the NewRandomObject function at different times.

  2. I don't like the fact that the NewRandomObject function has to call itself over and over to find a new object if its already active. I was wondering if there's a way to check the objects array and grab only inactive objects?

It works for what I need it to do and was just wondering if y'all had any ideas that could make it cleaner and more efficient.

 using UnityEngine;
 using System.Collections;
 
 public class ObjectTimer : MonoBehaviour {
 
     private GameObject[] objects;
     private GameObject randomObjects;
     private int clock = 0;
     
     private void Start()
     {
         objects = new GameObject[transform.childCount];
         for (int i = 0; i < transform.childCount; i++)
         {
             objects[i] = transform.GetChild(i).gameObject;
         }
         StartCoroutine("objectClock");
     }
     
     private IEnumerator objectClock()
     {
         while (true)
         {
             yield return new WaitForSeconds(1);
             clock ++;
             Debug.Log (clock);
             if(clock == 1)
             {
                 NewRandomObject();
             }
             if(clock == 5)
             {
                 NewRandomObject();
             }
             if(clock == 10)
             {
                 NewRandomObject();
             }
             if(clock == 15)
             {
                 NewRandomObject();
             }
             if(clock == 20)
             {
                 NewRandomObject();
             }
             if(clock == 25)
             {
                 NewRandomObject();
             }
             if(clock == 30)
             {
                 NewRandomObject();
             }
             if(clock == 35)
             {
                 NewRandomObject();
             }
         }
     }
     
     private void NewRandomObject()
     {
         randomObject = objects[Random.Range(0, objects.Length)];
         if(randomObject.activeInHierarchy == true)
         {
             Debug.Log("Object already active; finding new object");
             NewRandomObject();
         }
         else
         {
             randomObject.SetActive(true);
         }
     }
 }
 

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
1
Best Answer

Answer by Hellium · Jul 14, 2015 at 12:39 PM

This is what I would have done :

  using UnityEngine;
  using System.Collections;
  
  public class ObjectTimer : MonoBehaviour {
  
      private GameObject[] objects;
      private GameObject randomObjects;
      private int clock = 0;
      
      private void Start()
      {
          objects = new GameObject[transform.childCount];
          for (int i = 0; i < transform.childCount; i++)
          {
              objects[i] = transform.GetChild(i).gameObject;
          }
          StartCoroutine("objectClock");
      }
      
      private IEnumerator objectClock()
      {
          for( int clock = 0 ; clock < 36 ; ++ clock )
          {
              yield return new WaitForSeconds(1);
              if( ( clock % 5 ) == 0)
              {
                  NewRandomObject();
              }
          }
      }
      
      private void NewRandomObject()
      {
         int startIndex = Random.Range( 0, objects.Length );
         int index = 0;
         
         // Look for the first active object starting at a random index
         for ( index = startIndex ; !objects[Random.Range(0, objects.Length)].activeInHierarchy ; ++index )
         {
             // Prevent infinite loop
             if ( index - startIndex > objects.Length )
                 return ;
         }
         
         randomObject = objects[index] ;
      }
  }
Comment
Add comment · Show 4 · 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 Kody Birchfield · Jul 14, 2015 at 02:40 PM 0
Share

Where would you activate the randomly selected object, and what if you wanted to customize the clock to activate one random object at, say, 3 seconds and another at 8 seconds?

avatar image Hellium · Jul 14, 2015 at 02:47 PM 1
Share

Oops, I missed the first point. Didn't see it. I changed the condition inside the for loop then.

  private void NewRandomObject()
   {
      int startIndex = Random.Range( 0, objects.Length );
      int index = 0;
      
      // Look for the first inactive object starting at a random index
      for ( index = startIndex ; objects[Random.Range(0, objects.Length)].activeInHierarchy ; ++index )
      {
          // Prevent infinite loop
          if ( index - startIndex > objects.Length )
              return ;
      }
      
      objects[index].SetActive(true) ;
   }

About the clock, if you don't want it to be regular, define a public array of int / floats called spawnTimes, and modify the coroutine as follow :

  private IEnumerator objectClock()
   {
       for( int clockIndex = 0 ; clockIndex <= spawnTimes.Length ; ++clockIndex )
       {
           yield return new WaitForSeconds(spawnTimes[clockIndex ]);
           NewRandomObject();
       }
   }

Then, in your inspector, you can specify the different times you want the NewRandomObject() to be called.

avatar image Kody Birchfield · Jul 14, 2015 at 03:10 PM 0
Share

That is beautiful thank you so much

avatar image Hellium · Jul 14, 2015 at 03:55 PM 0
Share

I made a mistake in the for loop of the coroutine, make sure you have corrected it.

(I edited my last comment)

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Unsuccessfully trying to clamp my player object 0 Answers

Weird functioning lists 0 Answers

C# Creating a More Efficient Script 4 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