The cover for Non-static method requires a target

Non-static method requires a target

September 5, 2023

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.

How to fix the TargetException error

One of your methods is an instance method (it is not marked static). To fix it, use the static keyword.

What causes the TargetException 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 TargetException error?

You need to use the static keyword with your method. Here’s an example:

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.

Want to build better games?

© 2024