- Home /
How do I synchronise different objects turning on and off?
Apologies in advance if this is moronically simple but I'm stuck in trying to synchronise different game objects turning off and on together on different timers.
I have a game obstacle (called a Death Wall) with a variable for the time it's 'on' (which kills the player on contact) and a time it's 'off'. My problem is keeping multiple instances of this object in sync with eachother when they're on different time spans. For example if one is set at 0.5 duration to be on and 0.5 duration to be off, and a second one is set at 1.0 on and 1.0 off, the second one will initially flick on and off perfectly in time with two cycles of the first, but over time it will lag behind and no longer be in sync.
Here's the current code:
public class deathWallFinal : MonoBehaviour
{
public float startDelay;
public float OnTime;
public float OnTimer;
public float OffTime;
public float OffTimer;
public float lifeCounter;
public GameObject wall;
public BoxCollider2D death;
public GameObject DWG;
public GameObject DWGtop;
public GameObject particleLeft;
public GameObject particleRight;
// Start is called before the first frame update
void Start()
{
death = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
if (startDelay > 0)
{
startDelay = startDelay - 1*Time.fixedDeltaTime;
wall.GetComponent<SkeletonAnimation>().AnimationName = "off";
death.enabled = false;
}
if (startDelay <= 0)
{
if (OnTimer > 0)
{
OnTimer = OnTimer - 1 * Time.fixedDeltaTime;
OffTimer = OffTime;
death.enabled = true;
DWGtop.GetComponent<SkeletonAnimation>().AnimationName = "on";
DWG.GetComponent<SkeletonAnimation>().AnimationName = "on";
wall.GetComponent<SkeletonAnimation>().AnimationName = "on";
particleLeft.SetActive(true);
particleRight.SetActive(true);
}
if (OnTimer <= 0)
{
OffTimer = OffTimer - 1 * Time.fixedDeltaTime;
death.enabled = false;
DWGtop.GetComponent<SkeletonAnimation>().AnimationName = "off";
DWG.GetComponent<SkeletonAnimation>().AnimationName = "off";
wall.GetComponent<SkeletonAnimation>().AnimationName = "off";
particleLeft.SetActive(false);
particleRight.SetActive(false);
}
if (OffTimer <=0)
{
OnTimer = OnTime;
}
}
Sorry if this is an annoying question or isn't well articulated. Any help would be greatly appreciated :)
Answer by DrawMen1999 · Sep 12, 2019 at 05:36 PM
You could use a coroutine to just waitForSeconds before turning it on/off, their timing should be good.
void Update(){
On();
Waiting(onTime);
Off();
Waiting(offTime);
}
IEnumerator Waiting(float waitTime)
{
yield return new WaitForSeconds(waitTime);
}
No luck unfortunately. I changed things over to coroutines but the same issue persists. If one is on for 1 second and off for 1 second, and a second obstacle is on for 2 seconds then off for 2 seconds, after a few cycles they're out of sync again
Your answer
![](https://koobas.hobune.stream/wayback/20220612212004im_/https://answers.unity.com/themes/thub/images/avi.jpg)