Non-static method requires a target

On this page

    The Error

    System.Reflection.TargetException: Non-static method requires a target.

    Introduction

    I recently encountered this error in Unity and wanted to take a few minutes to do a quick write-up. This error can be frustrating when it halts your project's progress. In this brief guide, I will delve into the cause of this error and how to resolve it.

    What do I need to know?

    "System.Reflection.TargetException: Non-static method requires a target."

    Long story short, one of your methods is non-static. To fix it, use the static keyword.

    What causes this error?

    This error occurs when you use a method or class attribute that depends on the target method being a static method.

    One example of a possible attribute is the [InitializeOnLoadMethod] attribute. This attribute tells Unity to run the decorated method when Unity loads. This attribute requires the method to be a static method. If the function is non-static, Unity will throw this error.

    Here's an example of a script that demonstrates this error in action.

    ```

    using UnityEditor;

    using UnityEngine;

    public class NonStaticMethodRequiresATarget : MonoBehaviour

    {

        [InitializeOnLoadMethod]

        public void OnLoadMethod()

        {

            Debug.Log("This method will not run!");

        }

    }

    ```

    You'll also see a warning if you hover over the OnLoadMethod name. "Method decorated with InitializeOnLoadMethod, RuntimeInitializeOnLoadMethod, or DidReloadScripts attribute must be static and parameterless."

    How do I fix this error?

    You need to use the static keyword with your method to fix this error.

    ```

    using UnityEditor;

    using UnityEngine;

    public class NonStaticMethodRequiresATarget : MonoBehaviour

    {

        [InitializeOnLoadMethod]

        public static void OnLoadMethod()

        {

            Debug.Log("This method works!");

        }

    }

    ``` 

    Conclusion

    As you can see, it's a straightforward issue with a simple fix. This error is uncommon. I'm the only one who has written about this error for Unity.

    I hope this write-up helped give some context to the issue. Decorators like InitializeOnLoadMethod expect the method to be static. If it's not static, you'll get an error.

    Now, you clearly understand the cause and the right approach to resolve it. So you can keep your project on track instead of getting stuck.

    Join our newsletter to get the latest updates
    Sign Up
    Share
    Michael Sacco
    Founder & CEO

    Michael Sacco is the Founder and CEO of OccaSoftware where he specializes in developing game assets for Unity game developers. With a background ranging from startups to American Express, he's been building great products for more than 10 years.

    Tags
    programming
    c sharp
    Unity Basics
    Unity Errors
    unity troubleshooting