- Home /
Auto Enabling and looping a script?
Hey guys, I'm a noobie at Unity and the syntax used for scripting. I know a little javascript so I wrote what I could of a script that could disable and enable a camera with a little delay. Here's what I came up with.
function Start()
{
GameObject.Find("Main Camera").camera.enabled = false;
yield WaitForSeconds(.05);
GameObject.Find("Main Camera").camera.enabled = true;
yield WaitForSeconds(5);
}
Problem is, I have no clue where to go from there, as I need to have it loop and be running from the start. Any help? :D
Thanks, and sorry for being such a noob (sidenote, if someone could point me to some good basic video tutorials that would be great)
--Merglyn
Here is a list of tutorials to get you going :
Start at the bottom and work up : http://www.unity3dstudent.com/category/modules/
the Unity Wiki : http://wiki.unity3d.com/index.php/Tutorials
A list of resources : http://answers.unity3d.com/questions/12321/how-can-i-start-learning-unity-fast-list-of-tutori.html
Also look at the Unity Scripting Reference : http://docs.unity3d.com/Documentation/ScriptReference/index.html
use the search bar in the top-left, eg type in InvokeRepeating then click on the first link : http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$onoBehaviour.InvokeRepeating.html
this is one way to loop something, but usually anything that keeps getting executed is placed in an Update function :
function Update()
{
// do stuff every frame
}
This helped a bunch. Thanks.
The script reference helped a lot with Unity specific commands, but it was the general syntax that I was confused about... Thanks a bunch for the tuts though!
Answer by Toxic Blob · Feb 24, 2013 at 05:24 AM
CoRoutines are superbly helpful for this. Of course if you want to improve the performance of the script, you'll want to find your main camera in Start (so it happens only once). Cache the found camera to a variable, then access it later in LoopCamera().
function Start()
{
StartCoroutine( LoopCamera() );
}
function LoopCamera() : IEnumerator
{
while( true )
{
GameObject.Find("Main Camera").camera.enabled = false;
yield WaitForSeconds(.05);
GameObject.Find("Main Camera").camera.enabled = true;
yield WaitForSeconds(5);
}
}
Perfect. I had seen CoRoutines in other posts on similar topics, but they didn't give any specifics on the syntax and how they worked... Thanks for the answer!
Another comment, it seems to work fine in the preview, but when I build and run it, it doesn't do anything... Any help?
Never$$anonymous$$d. Preview defaulted disabled cameras to black while build defaulted it to last frame. Ended up enabling another camera that was just aimed at a plane. Thanks again for the answer.