How i can i stop the repeating in this code (send class into method)?

Hey there, i want to know a solution for how i can stop writing the same lines of code again and again for other classes. I want to get rid of the if tree.

    public void Test<T>() where T : class
        {     
            if (typeof(T) == typeof(One))
            {
                One[] ones = FindObjectsOfType<One>();
                foreach (One o in ones)
                {   
                    Something();
                }
            }
    
            if (typeof(T) == typeof(Two))
            {
                Two[] twice = FindObjectsOfType<Two>();
                foreach (Two t in twice)
                {   
                    Something();
                }
            }
// same code for other classes 
        }

Calling it with something like this:

...
Test<One>();

Some help would be great :slight_smile:

Greets

You could use a collection to store the valid types. As you’ve written it, the following code should work:

    public class MyClass
    {
        private HashSet<Type> _types;

        public MyClass()
        {
            _types = new HashSet<Type>
            {
                typeof(One),
                typeof(Two)
            };
        }

        public void Test<T>() where T: UnityEngine.Object
        {
            if (_types.Contains(typeof(T)))
            {
                T[] objectsOfT = FindObjectsOfType<T>();
                foreach (var t in objectsOfT)
                {
                    Something();
                }
            }
        }

        // rest of the class
    }

updated for completeness based on @Bonfire-Boy 's comment