- Home /
Trying to implement synchronized laser system.
I am trying to implement 3 laser obstacle which activates and deactivates periodically after some time(one at a time). I have created a structure for storing obstacle and created an array of structure object.
public float sec = 5.0f;
[Serializable]
public struct LaserEntity {
public GameObject Laser;
}
[SerializeField]
LaserEntity[] LE;
private void Awake()
{
LE[0].Laser.SetActive(true);
}
private void Update()
{
laserprocess();
}
void laserprocess() {
for (int i = 0; i < LE.Length; i++)
{
StartCoroutine(Activate(sec, LE[i]));
}
}
IEnumerator Activate(float time, LaserEntity LE) {
LE[i].Laser.SetActive(true);
yield return new WaitForSeconds(time);
LE[i].Laser.SetActive(false);
}
// I guess it works well for the first iteration but not for remaining ones.
Answer by Mahir-Gulzar · Sep 06, 2018 at 07:52 AM
@uniqe Well there are several ways to do this. what you are doing right now is kinda messy i.e calling multiple coroutines in a frame. I would suggest to do something like this..
[Range(0.0f,5.0f)]
public float sec = 5.0f;
public bool randomize = false;
//[SerializeField]
//public struct LaserEntity
//{
// public GameObject Laser;
//}
// You can refactor the code to use stuct
[SerializeField]
GameObject[] LE;
int currentLaser = 0;
private void Awake()
{
LE[currentLaser].SetActive(true);
InvokeRepeating("invokeSync", sec, sec);
}
void invokeSync()
{
if(randomize)
{
currentLaser = Random.Range(0, LE.Length + 1);
}
if(currentLaser+1<LE.Length)
{
currentLaser++;
}
else
{
currentLaser = 0;
}
foreach(GameObject entity in LE)
{
entity.SetActive(false);
}
LE[currentLaser].SetActive(true);
}
As you can see I have added some extra functionality... Not only you can activate and deactivate them periodically but also randomize the order of activation.. Cheers :)
$$anonymous$$ore than what I can expect. Excellent. Randomization was my second hurdle.
It's contradicting for a single element. I will figure out myself for a single laser element.
Your answer
Follow this Question
Related Questions
How to gradually increase difficulty. 1 Answer
How to decrease gravityScale in period of time? 1 Answer
WaitForSeconds not waiting 1 Answer
Call another function during wait for seconds 1 Answer
WaitForSeconds using Update? 1 Answer