• 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 stavros_s · Nov 01, 2011 at 10:51 PM · loops

Continuous loop

Hey Everyone,

So I have a script that is intreating through different game objects on a timer. Its working properly but once it gets to the last game object it stops the scene. I would prefer if it would just start re-looping through them and continue doing this, here is what I have so far. Thanks for any help you guys can give.

var waitTime = 5;

var numberOfCameras = 4;

// Timed camera switch function function cameraLoop(){

 for (var i = 0; i< numberOfCameras;i++) {
     var oldCamera : GameObject = null;
        
     if (i == 0 ) oldCamera = GameObject.Find("cameraObj"+(i));
         Debug.Log("old Camera: cameraObj" + (i));
     
     var newCamera = GameObject.Find("cameraObj"+(i+1));
         Debug.Log("new Camera: cameraObj" + (i+1));

     yield WaitForSeconds(waitTime);
         Debug.Log("It yielded");

     if(oldCamera) oldCamera.active = false;
         Debug.Log("camera" + i + " has been deactivated");
     
     newCamera.SetActiveRecursively (true);
         Debug.Log("camera" + (i + 1) + " has been activated");
            
 }

}

function Update () {

 cameraLoop ();

}

EDITED1: hmm I keep getting the follwoing error :

NullReferenceException UnityEngine.GameObject.SetActiveRecursively (Boolean state) cameraTimer+$Start$7+$.MoveNext () (at Assets/scripts/cameraTimer.js:17)

While using this script :

var waitTime: float = 5; var numberOfCameras = 4;

function Start(){ var curCamera:GameObject = null; var i:int = 0;

 while (true){ // loop forever
 
     // deactivate current camera, if any
     if (curCamera) curCamera.SetActiveRecursively(false);
     
     // get the next camera
     curCamera = GameObject.Find("camera"+i);
     
     // activate it
     curCamera.SetActiveRecursively(true);
     
     // wait 
     yield WaitForSeconds(waitTime);
     
     // prepare pointer to the next camera
     i += 1;
     
     // if numberOfCameras reached, reset pointer to the first camera
     if (i >= numberOfCameras) i = 0; 
 }

}

The way I have the gameObejects set up is that each gameObject has a camera in it as a child, this camera is running its own script that rotates around a model in the scene. The scene currently only has 3 models in it and each model has a camera rotating around it that is in an empty game object. I have the script to switch between the different empty gameObjects attached to the first camera in the first gameObject.

EDITED2: So I managed to change some things and have it switching to the next camera after it deactivates the first but it wont move on to the third. The loop seems to be stoping right before the yield the second time around. Heres the new code. Sorry about all the post btw.

var waitTime: float = 3; var numberOfCameras = 3;

function Start(){

 var curCamera:GameObject = null;
 var i:int = 0;
 
 while (true){ // loop forever
   Debug.Log("starting Loop" +i);
  
     // deactivate current camera, if any
     if (curCamera) curCamera.SetActiveRecursively(false);
     
     // get the next camera
     curCamera = GameObject.Find("cameraObj"+i);
       Debug.Log("cameraObj"+i);
     
     // activate it
     curCamera.SetActiveRecursively(true);
       Debug.Log("activated Camera"+ curCamera); 
     
     // wait 
       Debug.Log("before yield"+i);
     yield WaitForSeconds(waitTime);
       Debug.Log("yielded"+i); 
     
     // prepare pointer to the next camera
     i += 1;
     
     // if numberOfCameras reached, reset pointer to the first camera
     if (i >= numberOfCameras) i = 0; 
 }

}

Comment
Add comment · Show 3
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 aldonaletto · Nov 02, 2011 at 08:23 PM 0
Share

@stavros_s, please use add new comment to post comments or replies, or edit your question to include new information. Don't use the Your answer box - it must be used only to answer the question. I edited your question to add your replies, and deleted the answers to avoid a big confusion.

avatar image aldonaletto · Nov 02, 2011 at 08:45 PM 0
Share

Now, your problem: it seems that one of the cameras cannot be found, what is producing the error. You could change the code to this:

var waitTime: float = 5;

function Start(){ var curCamera:GameObject = null; var i:int = 0; while (true){ if (curCamera) curCamera.SetActiveRecursively(false); curCamera = GameObject.Find("cameraObj"+i); if (curCamera){ // if camera found... curCamera.SetActiveRecursively(true); yield WaitForSeconds(waitTime); i += 1; } else { // if no more cameras found... i = 0; // return to the first one } } } This way you don't need to worry about the numberOfCameras - the script looks for cameraObj0, cameraObj1, cameraObj2, cameraObj3 etc. If "cameraObj3" can't be found, for instance, the script returns to "cameraObj0".

avatar image stavros_s · Nov 03, 2011 at 05:50 AM 0
Share

Sorry about that, didn't even see the comment button, thanks for pointing it out and fixing the post for me. Bigger thanks for all the help you have been giving me with this script, I appreciate it ! Now to go tinker around with it some more and try this new method you just showed me.

4 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by WillTAtl · Nov 01, 2011 at 10:58 PM

you should be able to just replace the for(...) loop with a while(true). Define the variable i just before while(), initialized to 0, then at the end of the loop, just before the final }, add 1 to i, then test if i is equal to numberOfCameras. If it is, reset it to 0, and the next pass through the loop will start over.

Not part of your question, but you probably want to call cameraLoop() in Start() rather than Update(), while you're at it. The function, once called, will keep running, so there's no reason to call it again every frame.

Comment
Add comment · 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
1

Answer by aldonaletto · Nov 01, 2011 at 11:21 PM

You're calling the coroutine cameraLoop inside Update - this makes a new cameraLoop coroutine be started each frame!
You could make the cameras loop from one to another in a simpler way, and without creating multiple coroutines:

var waitTime: float = 5; var numberOfCameras = 4;

function Start(){ var curCamera:GameObject = null; var i:int = 0; while (true){ // loop forever // deactivate current camera, if any if (curCamera) curCamera.SetActiveRecursively(false); // get the next camera curCamera = GameObject.Find("camera"+i); // activate it curCamera.SetActiveRecursively(true); // wait yield WaitForSeconds(waitTime); // prepare pointer to the next camera i += 1; // if numberOfCameras reached, reset pointer to the first camera if (i >= numberOfCameras) i = 0; } }

Comment
Add comment · Show 2 · 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 WillTAtl · Nov 01, 2011 at 11:27 PM 0
Share

yawp, pretty much exactly like that, heh. Doing it entirely in Start() is clever, I forget that since it's just called once, it can be a coroutine. An old saying about $$anonymous$$ching a man to fish comes to $$anonymous$$d, though... :)

avatar image aldonaletto · Nov 02, 2011 at 02:06 AM 1
Share

he knows how to fish, but showing a more efficient way may help him to improve his technique

avatar image
1

Answer by Peter G · Nov 01, 2011 at 11:32 PM

Your game might be freezing because of the ridiculous number of unnecessary coroutines you have going. You are starting a new coroutine every frame. So by the time the first loop gets to the 4th camera, 20 seconds have gone by. That's 20secs * 30FPS = 600 coroutines running at the same time. Four of which will be changing the camera. Basically, you are over looping.

You might just want to use InvokeRepeating() for this. It calls a given function at a specific interval.

 var waitTime : int = 5;
 var numberOfCameras = 4;

 private var curCamera : int = 0;
 function Start () {
      InvokeRepeating("CameraLoop" , waitTime , waitTime);
 }
 function CameraLoop () {
      var oldCamera = GameObject.Find("cameraObj (" + curCamera.ToString() + ")" );
      oldCam.active = false;
 

      //Add one to the counter.
      curCamera = ++curCamera  % numberOfCameras;
      //make sure we don't go over the number of cameras we have.
 
      var newCam = GameObject.Find("cameraObj (" + curCamera.ToString() + ")" );
      newCameraSetActiveRecursively (true);
 }
Comment
Add comment · 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
0

Answer by stavros_s · Nov 02, 2011 at 08:03 PM

So I managed to change some things and have it switching to the next camera after it deactivates the first but it wont move on to the third. The loop seems to be stoping right before the yield the second time around. Heres the new code. Sorry about all the post btw.

var waitTime: float = 3;

var numberOfCameras = 3;

function Start(){

 var curCamera:GameObject = null;
 var i:int = 0;
 
 while (true){ // loop forever
   Debug.Log("starting Loop" +i);
  
     // deactivate current camera, if any
     if (curCamera) curCamera.SetActiveRecursively(false);
     
     // get the next camera
     curCamera = GameObject.Find("cameraObj"+i);
       Debug.Log("cameraObj"+i);
     
     // activate it
     curCamera.SetActiveRecursively(true);
       Debug.Log("activated Camera"+ curCamera); 
     
     // wait 
       Debug.Log("before yield"+i);
     yield WaitForSeconds(waitTime);
       Debug.Log("yielded"+i); 
     
     // prepare pointer to the next camera
     i += 1;
     
     // if numberOfCameras reached, reset pointer to the first camera
     if (i >= numberOfCameras) i = 0; 
 }

}

Comment
Add comment · 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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

dosent work 0 Answers

Sequential Coroutines sometimes halt 1 Answer

My loop isn't working??? (C#) (Need help please) 1 Answer

Problem with looping concatenation with custom class 1 Answer

Lerping & OnCollisionEnter - how do i lerp without update?? 1 Answer


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