- Home /
How do I use Yield in C#?
How does one use yield in C#. It behaves differently then the Javascript version of yield.
I was trying to convert this Javascript example to C#. It doesn't seem to call the corfunAlp routine. Help!
using UnityEngine; using System.Collections;
public class fader : MonoBehaviour {
public GameObject gamobjBac;
Color thecolor;
// Use this for initialization
void Start ()
{
corfunAlp (gamobjBac, 0, 1, 1);
// Turn opaque
corfunAlp (gamobjBac, 4, 1, 0);
// Turn transparent
}
// Update is called once per frame
void Update ()
{
}
//function that fades alpha for a game object up or down with a start delay and duration of fade
public IEnumerator corfunAlp (GameObject gamobjGamObj, float floWai, float floDur, int intAlpGoa)
{
float floAlp = (1 - intAlpGoa);
intAlpGoa = ((2 * intAlpGoa) - 1);
yield return new WaitForSeconds (floWai);
while (floAlp >= 0 && floAlp <= 1)
{
thecolor = gamobjGamObj.renderer.material.GetColor ("_Color");
thecolor.a = floAlp;
gamobjGamObj.renderer.material.SetColor ("_Color", thecolor);
floAlp = floAlp + ((Time.deltaTime/floDur)*intAlpGoa);
yield return true;
}
}
}
Answer by Murcho · Nov 22, 2009 at 04:44 PM
You need to manually call StartCoroutine() for C# coroutines. That information is provided in the documentation here.
To use it in you example, simply change your Start function as follows.
// Use this for initialization
void Start ()
{
StartCoroutine(corfunAlp (gamobjBac, 0, 1, 1));
// Turn opaque
StartCoroutine(corfunAlp (gamobjBac, 4, 1, 0));
// Turn transparent
}
Answer by equalsequals · Nov 22, 2009 at 07:53 PM
Murcho is correct. But for additional help I wrote this tutorial awhile back on Coroutines for both JS and C#:
http://infiniteunity3d.com/2009/09/27/tutorial-coroutines-pt-1-waiting-for-input/
Hope that helps!
Thank you, that was very helpful! I'm sure you're busy, please add the screen shots back in if you ever have the time.
Haha - you have no idea. I was hoping to get to that some time this evening if I can!
Just an FYI I was able to get those images back into the blog post last night. Cheers!
I really appreciate it. This was just a case of perfect ti$$anonymous$$g as I was just starting to puzzle over coroutines. Thanks again!
FYI, @equalsequals, not that you haven't done plenty already, but you may be interested in this tool by google called Google code Prettify. I've used it before and its quite easy, just add the JS and it will do code coloring for your example code: http://code.google.com/p/google-code-prettify/
Answer by synapsemassage · Jul 16, 2011 at 11:11 AM
And there is even some more info in the docs. Here.
Your answer
Follow this Question
Related Questions
Waiting for input using yield and coroutines 1 Answer
StartCoroutine important for using yield? 1 Answer
How to use yield within a class function 2 Answers
JS Wait for a function to complete - no WaitForSeconds 1 Answer
Coroutines and states 1 Answer