Question by
Hensn · Feb 09, 2017 at 07:14 PM ·
lightcoroutinespickups
Decreasing Light in Coroutine after Pickup
Hello, I'm new to Unity and programming. I'm trying to do the following: The player picks up a torch. Then the torches light-intensity slowly decreases until the torch is out. I figured this could be done with coroutines. This was my attempt:
public class PlayerTorchScript : MonoBehaviour {
Transform Torch;
Transform Player;
Transform PlayerTorch;
bool HasTorch;
float TorchIntensity;
Light LightComponent;
void Start ()
{
Player = GameObject.FindGameObjectWithTag ("Player").GetComponent<Transform>();
PlayerTorch = Player.GetChild (1);
HasTorch = false;
}
//Here the player picks up the torch
public void OnMouseDown()
{
if ((transform.position - Player.position).magnitude < 3) {
Destroy (transform.gameObject);
PlayerTorch.gameObject.SetActive (true);
HasTorch = true;
LightComponent = PlayerTorch.GetComponentInChildren<Light> ();
StartCoroutine (HasPlayerTorch ()); //Coroutine starts here
}
}
IEnumerator HasPlayerTorch ()
{
while (LightComponent.intensity > 0f) {
LightComponent.intensity = LightComponent.intensity - 0.25f;
yield return new WaitForSeconds (1f);
}
}
}
When this script runs it decreases the light-intensity once by 0.25 units and then stops working, even though there's a while-loop. Can someone tell me what I'm doing wrong? I've tried starting the coroutine from the start and update funtion with the same problems.
Thanks in advance!
Comment