Search code examples
c#androidunity-game-enginetimermessage

Unity CSharp - Timer & Broadcast Message


I personally could not find the answer on stackoverflow already, but my question is kind of basic, I just don't understand what I need to do in this scenario: If I have the following code, how would I use BroadcastMessage so that when my timer (myCT) is equal to 500 it displays a message in unity, Thanks.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class myTimer : MonoBehaviour 
{
  public float myCT = 600;
  public Text timerText;


  void Start () {
    timerText=GetComponent<Text>();
  }

  // countdown
  void Update () {
    myCT -= Time.deltaTime;
    timerText.text = myCT.ToString("f0");
    print (myCT);

    if(myCT = 598){
      //I want something to happen here using broadcast message()
    }
  }
}

Solution

  • This looks like a countdown timer that is counting from 600 down to 500.First of all, you compare stuff with == (if(myCT = 598){}) not with =. Because myCT is a float, it is never guaranteed to be 598 or 500 when decreasing. So you must use <= instead of ==.

    if(myCT = 598){
    
    }
    

    should be

    if(myCT <= 500){
        Debug.Log("Timer reached!");
        BroadcastMessage("doSomthingFunction", 500.0F);
    }