Hello I made an array with VFX gameobjects and get vfx property of it to assigned with slider value but somehow only one of gameobjects value update. Can someone help me to explain why this script is not work properly and how to fix? Thank you!
{
public GameObject[] vfxs;
Slider slider;
float sliderVal;
VisualEffect vfxval;
// Start is called before the first frame update
void Start()
{
vfxs = GameObject.FindGameObjectsWithTag("VFX");
foreach (GameObject vfx in vfxs)
{
vfxval = vfx.GetComponent<VisualEffect>();
}
slider = this.GetComponent<Slider>();
}
// Update is called once per frame
void Update()
{
sliderVal = slider.value * 100;
vfxval.SetFloat("Power", sliderVal);
}
}
CodePudding user response:
You collect the objects in Start, but you overwrite the value of "vfxval" in the foreach
loop multiple times. In the end, you only have a single instance reference by that variable, that you use in Update
...
I suggest you do this:
public VisualEffect[] vfxsVals;
Slider slider;
float sliderVal;
// Start is called before the first frame update
void Start()
{
GameObject[] vfxs = GameObject.FindGameObjectsWithTag("VFX");
foreach (GameObject vfx in vfxs)
{
vfxsVals.Add(vfx.GetComponent<VisualEffect>()); // collect all VisualEffect instances
}
slider = this.GetComponent<Slider>();
}
// Update is called once per frame
void Update()
{
sliderVal = slider.value * 100;
foreach (GameObject in vfxsVals)
{
vfx.SetFloat("Power", sliderVal); // set value on ALL instances.
}
}
It's faster to reuse the list of VisualEffects instead of calling "FindGameobjects..." or ".GetComponent<>" every frame - because they are slow. It's ok to do this in Start
.
Bonus: You could use tryGetComponent to avoid errors/crashes.