- Home /
how can avoid repeat logic in these methods
i have these 2 methods that have the same behavior and i want to make a single function Opacador that can change the color as much for the text as for the image. The problem is that i cannot replace the signature for IEnumerator Opacador (float ... ,Gameobject objeto)
because Gameobject can't do Color colorActual = objeto.color
. I also tried Color colorActual = gameObject.GetComponent<Renderer>().material.color
but this gave me error. is there anything i can do?
Answer by JxWolfe · Apr 09, 2020 at 10:02 PM
IEnumerator Opacador(float timpDeColorado, float aphaFinal, Image objeto) {
//Opacador code
}
IEnumerator Opacador(float timpDeColorado, float aphaFinal, TextMeshProUGUI objecto) {
//OpacadorDeTilulo code
}
this is how you take multiple arguments. Like how Destroy(gameObject) and Destroy(gameObject, time). This means that when Opacador gets called, depending on what arguments you feed it will determine how which IEnumerator gets run.
Alternatively, you could use
IEnumerator Opacador(float timpDeColorado, float aphaFinal, bool useImage, GameObject item) {
//simalarities
if(useImage) {
Image img = item.GetComponent<Image>();
// image only code
}
else {
TextMesPro txt = item.GetComponent<TextMeshPro>();
//TextMeshPro only code
}
}
This could also work. However, it would be worse when you call it. (overcomplicated)
But in the first case you're also repeating logic that it is what i want to avoid. Do you think that is better to repeat logic ins$$anonymous$$d of overcomplicated the method? (because the second option is not very OOP)
Sorry for not getting back to you, ran into a space issue and somehow firefox reset. (idk) Option A is far superior to option B. It's better to repeat logic than try to round about it. The excess code will really only take up storage space, it won't dampen processing power, (option B would). If you use #region and #endregion tags, they won't even need to display when you are coding. Option A is how unity's default functions are written, and I would follow suit, even if it's just for consistency.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Why Dose not this work (IEnumerator) 1 Answer
Changing a string in a loop each second 3 Answers
Images don't load after building. 1 Answer
Why is it that when I pass this variable to an IEnumerator, it stops working? 1 Answer