Hi,
For the life of me I can’t get this code to do as I want! I used this code in another part of my unity project and the behaviour I wanted worked. Unfortunately I needed to use prefabs so I have had to remove the script an alter it slightly so that it could be added to the prefab and the prefab then instantiated from another script. - Technically this should work but it just does not and I cannot understand why?
This is score text that should appear on screen, move upwards whilst it’s Alpha is being reduced (to fade out) and then the instantiated prefab is destroyed.
For the time being I have just attached the script to the prefab and added the prefab to the scene. In theory I should be seeing this prefab (at game start) move upwards, fade and then be destroyed. All that happens is the prefab sits there and then destroys itself. - So I know that the coroutine is being triggered, but why are the other elements not working correctly?
I think I am really misunderstanding how coroutines fundamentally work, but I just can’t my head around the unity examples on this any help would be much appreciated!!!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TextPop : MonoBehaviour {
Image image;
RectTransform rectTransform;
bool started;
public float fadeTime = 1.0f;
void Start () {
fadeTime = 1.5f;
image = GetComponent<Image> ();
rectTransform = GetComponent<RectTransform> ();
started = false;
}
void Update () {
if (!started) {
StartCoroutine ("FadeCycle");
started = true;
}
}
// This coroutine will fade the target sprite Alpha value and move the position
IEnumerator FadeCycle () {
float fade = 1f;
float startTime;
startTime = Time.time;
while (fade > 0f) {
fade = Mathf.Lerp (1f,0f, (Time.time - startTime) / fadeTime);
image.color = new Color (1f,1f,1f,fade);
rectTransform.transform.position = new Vector3 (rectTransform.transform.position.x, rectTransform.transform.position.y + 1, rectTransform.transform.position.z);
yield return new WaitForSeconds (2);
Destroy (this.gameObject);
}
}
}