Home > other >  Call method without using static class name before method name c#
Call method without using static class name before method name c#

Time:09-23

My question is - How can i call my method GetISystemManager without using class name References before Method name? Why is this possible in the first example, but not in the second?

  1. If I use the UnityEngine namespace in a Unity project, I can use method e.g. FindObjectOfType without specifying any static class before the method name:

Method:

public static T FindObjectOfType<T>() where T : Object;

Call:

cM = FindObjectOfType<CameraManager>();
  1. I created a similar method which is in my static class References, but I can only call it with "References." before the method name.

Method:

 public static T GetISystemComponent<T>() where T : ISystemComponent
    {
        foreach(ISystemComponent sC in systemComponentList)
        {
            if(sC.GetType().Equals(typeof(T)))
            {
                return (T)sC;
            }
        }
       Debug.LogError(typeof(T)   " - this component not exist in systemComponentList." );
       return default(T);
    }
       

Call:

mM = Reference.GetISystemComponent<MazeManager>();

This is a method i am talking about in Unity. enter image description here

CodePudding user response:

Your class of the first example most probably inherits from MonoBehaviour or ScriptableObject which both inherit from UnityEngine.Object -> it is a UnityEngine.Object and can therefore directly use its methods.


Besides that and in general you can also always add a using static <namespace.type>

using static UnityEngine.Object;

on top of a script and then use any static method (actually member) of UnityEngine.Object without everytime writing UnityEngine.Object in front of it.

  • Related