- Home /
The question is answered, right answer was accepted
How do I repeat a part of my script?
I want to repeat a part of my code:
function Start(){
guiText.material.color.a = 0;
yield WaitForSeconds(3);
FadeIn();
}
function FadeIn(){
while (guiText.material.color.a < 1){
guiText.material.color.a += 0.1 * Time.deltaTime * 10;
yield;
}
yield WaitForSeconds(0.1);
FadeOut();
}
function FadeOut(){
while (guiText.material.color.a > 0){
guiText.material.color.a -= 0.1 * Time.deltaTime * 10;
yield;
}
}
I want to repeat the "FadeIn" and "FadeOut" parts, how will I be able to do that? I tired StartCoroutine, but it was just to difficult...
Answer by Ermarrero · Apr 05, 2014 at 04:59 PM
Just make a
function Update()
{
FadeIn();
FadeOut();
}
Replace the while loop to a if statement. Also remove FadeOut () from the FadeIn (), thats no longer needed.
Have you thought about putting them both in one function instead of two?
Another thing you can do and its reallly simple is using Mathf.PingPong. See below:
Heres a reallllly simple solution:
public class TextFader : MonoBehaviour
{
public GUIText text;
public float speed = 1f;
public Color color;
void Start ()
{
if(text == null)text = this.gameObject.GetComponent<GUIText>();
if(text == null)Debug.Log("Please attach this script to a gameobject with a GUIText component or assign one manually to this.");
}
void Update ()
{
if (text != null)
{
text.color = color;
color.a = Mathf.PingPong(Time.time / speed, 1);
}
}
}
https://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$athf.PingPong.html
Look at this mathf class espcially the pingpong. It will do what you need on one line of code.
Heres a reallllly simple solution:
public class TextFader : $$anonymous$$onoBehaviour
{
public GUIText text;
public float speed = 1f;
public Color color;
void Start ()
{
if(text == null)text = this.gameObject.GetComponent<GUIText>();
if(text == null)Debug.Log("Please attach this script to a gameobject with a GUIText component or assign one manually to this.");
}
void Update ()
{
if (text != null)
{
text.color = color;
color.a = $$anonymous$$athf.PingPong(Time.time / speed, 1);
}
}
}
Answer by 0V3RR1D3 · Apr 06, 2014 at 01:04 AM
Or
function FadeIn(){
while (guiText.material.color.a < 1){
guiText.material.color.a += 0.1 * Time.deltaTime * 10;
yield;
}
yield WaitForSeconds(0.1);
FadeOut();
}
function FadeOut(){
while (guiText.material.color.a > 0){
guiText.material.color.a -= 0.1 * Time.deltaTime * 10;
yield;
}else{
FadeIn();
}
}
Follow this Question
Related Questions
Trying to Loop A Function 2 Answers
Fade Float Function 2 Answers
Repeat a function only when an action occurs 1 Answer
Looping a function 1 Answer