What is the syntax to pass any kind of class at all into a method?

public static void SingletonInstance (AnyTypeOfClass?? class)

What do I put where “AnyTypeOfClass” is to make this work?

It all sort of depends on what you’re attempting to actually do.

Are you trying to get the ‘type’ information?

public static void AcceptATypeGenerically<T>()
public static void AcceptATypeAsATypeObject(System.Type tp)

Or are you trying to pass in an instance of any type?

public static void PassAnyObjectOfType<T>(T instance)
public static void PassAnyObjectOfTopMostParentType(System.Object instance)

But again… I don’t know what you’re actually asking for.

What do you want this method you’re attempting to write do?

In C#, there’s a special class that is a superclass of all other classes, called “object” (or System.Object). So if you have void MyFunction(object arg) then you can pass in absolutely any class as the argument when calling it.

But note that this isn’t good for much. There’s very little you can DO with an “object”, since you don’t know anything about it. You can only do things with it that would be legal to do with literally any class, including hypothetical classes that aren’t actually defined in your program. Basically, you can convert it to a string, test if it’s equal to another object, or attempt to dynamically cast it to a more specific type.

And I’m not sure why you wrote in your example, or what you’re trying to do with that. Are you trying to do something like CRTP?

    public static GameGlobalManager Instance { get; private set; }

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

I am trying to refactor this block of code. Its the code I run on every singleton. I copy and paste it to every Singleton. I want to stop copy pasting it and move it to a Utils method, but I can’t figure out how to do that because I can’t figure out how to pass in any possible class to the method instead of an explicit class, for example “GameGlobalManager” as above.

As lordofduct explained, the way to do this are Generic Types (that “” stuff). Basically T stands for whatever type you want and the “where T : Component” stuff limits what T can be (in order for it to be usable without casting and limit input).

Here is an example of generic singletons you can inherit from (I just googled for “unity generic singleton”):

You asked a question about function arguments, and then posted example code that doesn’t involve any functions that accept arguments.

1 Like