- Home /
Question by
ItArth · Jan 31, 2020 at 01:14 AM ·
scripting problemimage effects
Add a component 1 time in LateUpdate
I have the GrayScale Image Effect, that put all the screen white and black, so i have too in my LateUpdate void that when my Life is lower that 16 I add the GrayScale effect to the MainCamera, but this GrayScale is added infinitely how i can add it 1 time? this is my Script:
void LateUpdate()
{
LowLife();
}
void LowLife()
{
Grayscale grayscale;
if (currentHealth <= lowLife)
{
Camera.main.gameObject.AddComponent<Grayscale>(); // Add the GrayScale
if (!lowLifeSource.isPlaying && !dead)
{
lowLifeSource.clip = heartClip;
lowLifeSource.Play();
}
}
else
{
if (!dead)
{
lowLifeSource.Stop();
}
}
}
Comment
Answer by Fariborzzn · Jan 31, 2020 at 03:09 AM
try this:
if(Camera.main.gameObject.GetComponent<Grayscale>()==null)
{
Camera.main.gameObject.AddComponent<Grayscale>();
}
Answer by logicandchaos · Jan 31, 2020 at 03:12 AM
if(Camera.main.gameObject.GetComponent()==null)
Camera.main.gameObject.AddComponent();
Answer by IINovaII · Jan 31, 2020 at 03:22 AM
Running GetComponent() method during every frame is a terrible idea. Instead, introduce a bool field to your script which changes its state depending on if GrayScale is added or not. The code will look something like this.
private bool _isGrayScaleAdded;
void LateUpdate()
{
LowLife();
}
void LowLife()
{
Grayscale grayscale;
if (currentHealth <= lowLife)
{
//This part checks if you've already added it or not.
if(!_isGrayScaleAdded){
if(Camera.main.gameObject.GetComponent<GrayScale> == null)
Camera.main.gameObject.AddComponent<Grayscale>(); // Add the GrayScale
_isGrayScaleAdded = true; //Changing this value to true makes sure it won't be added again and also makes sure GetComponent method won't be called again
}
if (!lowLifeSource.isPlaying && !dead)
{
lowLifeSource.clip = heartClip;
lowLifeSource.Play();
}
}
else
{
if (!dead)
{
lowLifeSource.Stop();
}
}
}