Monday, April 28, 2025
HomeGame Developmentunity - Singleton implementation/use difficulty

unity – Singleton implementation/use difficulty


I am kind of starting developer and I am presently engaged on a 3D recreation undertaking with third individual view.
After I carried out first ActionMap into my character controller, every part labored positive, PlayerControls object has been referred to as inside the category with enter callbacks and it was sufficient for strolling, sprinting, leaping, and so forth. However once I created one other ActionMap for actions(assault, collect, work together) and determined to maneuver PlayerControls implementation into one other, centralized script, every part crumbled down. Upon beginning play mode in unity I get a NullRefrenceException within the OnEnable cycle in PlayerLocomotionInput. After including some traces for debugging, I’ve discovered that Occasion is null originally of LocomotionInput OnEnable cycle, as well as, I do not see a DontDestroyOnLoad folder within the hierarchy throughout play mode.
What I used to be attempting to do, is to make a category InputManager, create a singleton to entry objects of this class and create PlayerControls object that may be accessed elsewhere:

public class InputManagerScript : MonoBehaviour
{
    public static InputManagerScript Occasion;

    public PlayerControls PlayerControls { get; personal set; }


    personal void Awake()
    {
        if (Occasion != null && Occasion != this)
        {
            Destroy(this.gameObject);
            return;
        }
        else
        {
            Occasion = this;
            DontDestroyOnLoad(gameObject);
        }
    }

    personal void OnEnable()
    {
        PlayerControls = new();
        PlayerControls.Allow();
    }

    personal void OnDisable()
    {
        PlayerControls.Disable();
    }
}

And a code pattern from the ActionMap enter script:

public class PlayerLocomotionInput : MonoBehaviour, PlayerControls.IPlayerLocomotionMapActions
{
    #area Variables and fields
    #endregion

    personal void OnEnable()
    {
        InputManagerScript.Occasion.PlayerControls.PlayerLocomotionMap.Allow();
        InputManagerScript.Occasion.PlayerControls.PlayerLocomotionMap.SetCallbacks(this);
    }

    personal void OnDisable()
    {
        InputManagerScript.Occasion.PlayerControls.PlayerLocomotionMap.Disable();
        InputManagerScript.Occasion.PlayerControls.PlayerLocomotionMap.RemoveCallbacks(this);
    } 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments