How can i avoid to repeating the same code for a different class?
Hey together, is there a proper way to avoid repeating the exactly same code (just for a different class?)
Here is the code:
public void DifferentClasses<T>() where T : class
{
if (typeof(T) == typeof(Class1))
{
Class1[] cs = FindObjectsOfType<Class1>();
foreach (Class1 c in c)
{
c.curLoadTime = 0;
c.loadingImage.fillAmount = 0;
}
}
if (typeof(T) == typeof(Class2))
{
Class2[] cs = FindObjectsOfType<Class2>();
foreach (Class2 c in cs)
{
c.curLoadTime = 0;
c.loadingImage.fillAmount = 0;
}
}
}
At least i want to have method were i can send in some classes at let them execute the same code.
Thank you
Answer by EDevJogos · Jan 23, 2017 at 06:46 PM
Create a interface with a method like DoSomething(); and implement it on the classes that you looking for, then in your generic just say that T has this interface implemented:
public void DifferentClasses<T>() where T : class : IMyInterface
With this then you can do:
T[] cs = FindObjectsOfType(typeof(T)) as T[];
foreach (T c in cs)
{
c.DoSomething();
}
For details on interface see:
Answer by HenryStrattonFW · Jan 23, 2017 at 06:29 PM
Yes, and you're already doing part of it, generic parameters, you are not limited to a single parameter!
So perhaps something like this would be of use.
public void DifferentClasses2<T, C>()
where T : class
where C : class
{
if( typeof( T ) == typeof( C ) )
{
C[] cs = FindObjectsOfType<C>();
foreach( C c in cs )
{
// Do stuff on C here
}
}
}
Just keep in mind, that as far as the compiler is concerned your foreach type of C will only have access to the things in the constrained base type (in this case class) So depending on what classes you are trying to work on here you may wish to constrain T and C to types that are a little higher up in the class hierarchy.
you could even call this from your different classes method if you wanted, like so.
public void DifferentClasses<T>() where T : class
{
DifferentClasses2<T, Class1>();
DifferentClasses2<T, Class2>();
DifferentClasses2<T, Class3>();
DifferentClasses2<T, Class4>();
// and so on, you get the idea.
}
Your answer
Follow this Question
Related Questions
How do I stop the player from shaking in Unity2D? 2 Answers
Unity crashes when compiling this script. Where is the problem? 0 Answers
Try part of C# not being Read 1 Answer
UnityCar - Controlling Speed with a duration? 2 Answers
How do I change the scene after 2 objects are destroyed (SetActive false) 1 Answer