- Home /
Question by
rocket350 · Apr 24, 2014 at 10:14 AM ·
c#class instancepublic static
Add a extension method to the class Application
I would like to create a extension method call ReloadLevel() for the class Application. I tried this:
public static void ReloadLevel(this Application app){
app.LoadLevel(app.loadedLevel);
}
It gives me an error(which doesn't suprise me):
Static member `UnityEngine.Application.loadedLevel' cannot be accessed with an instance reference, qualify it with a type name instead
I tried it with this:
public static void ReloadLevel(this Application app){
Application.LoadLevel (Application.loadedLevel);
}
But when I call the method with Application.ReloadLevel(), it gives me a error again:UnityEngine.Application' does not contain a definition for 'ReloadLevel'
What am I doing wrong?
Comment
Best Answer
Answer by vexe · Apr 24, 2014 at 10:19 AM
You don't create extension methods to call them statically - They need an instance to operate on so you call them via that instance.
public static void Reset(this Transform t)
{
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
}
// Somewhere else...
player.transform.Reset();
In your case, it doesn't make much sense to create an extension, because you don't create instances of Application
- instead, you should just create a Utils
class and have all your utility/helpers-related stuff there.
public static class Utils
{
public static void ReloadLevel()
{
Application.LoadLevel(Application.loadedLevel);
}
}