user2264784
user2264784

Reputation: 467

Unity extend SceneManager class

I try extend SceneManager class.

I write like here:

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public static class ExtensionMethods
{
    public static void LoadSceneWithSave(this SceneManager SceneManager) {
            Debug.Log("Debug LoadSceneWithSave");
    }
}

But when I try to use this new method:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.SceneManagement;

    public class SomeClass : MonoBehaviour 

    {

    void Start () {
        SceneManager.LoadSceneWithSave();
    }

}

It doesn't work.

Upvotes: 1

Views: 952

Answers (1)

Programmer
Programmer

Reputation: 125275

Yes, you can. Although, you will need to explicitly create instance of SceneManager class before you can use that new function(LoadSceneWithSave). An extension method requires an instance of the class to work.

This should work:

SceneManager mySeneManager = new SceneManager();
mySeneManager.LoadSceneWithSave();

How does the transform example you linked work without an instance?

It does have an instance. The reason why you need to create an instance of it and can't directly use it like you can with the Transform class:

public static class ExtensionMethods
{
    public static void ResetTransformation(this Transform trans)
    {
    }
}

...

public class SomeClass : MonoBehaviour 
{
    void Start () {
        transform.ResetTransformation();
    }
}

is because SceneManager is not declared in MonoBehaviour or any base class of MonoBehaviour. There is an instance of Transform class named transform that is declared in the Component class which Behaviour inherits from which MonoBehaviour inherits from.

Here is exactly what it looks like:

public class Object
{

}

public class Component : Object
{
    public Transform transform { get; } //This is declared
    //...Other variables
}

public class Behaviour : Component
{

}

public class MonoBehaviour : Behaviour
{

}

Finally, this is why you can use the transform variable to access its extension method like:

public class SomeClass : MonoBehaviour 
{
    void Start () {
        transform.ResetTransformation();
    }
}

because it was already declared and you inherited it from MonoBehaviour .

As you can see, SceneManager is not declared any where in the MonoBehaviour class or it's base classes and you need an instance of it to access any of its extension function.

Upvotes: 1

Related Questions