Toggling Script from another GameObject on/off Correctly using Unity Input System
I start the game being able to look and move around using a script called "Character_Control" attached to my "Player" gameobject. I can press escape to open a pause menu, and while I am in the pause menu, I want the "Character_Control" to be disabled so that I cannot control my player while the game is paused. I am using the unity input system.
I used the following code to toggle between the script being enabled/disabled, and it does toggle, however not the way I want it to:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Test : MonoBehaviour
{
private DefaultInput defaultInput;
public void Awake()
{
defaultInput = new DefaultInput();
gameObject.GetComponent<Character_Control>().enabled = true;
}
private void OnEnable()
{
defaultInput.Enable();
}
private void OnDisable()
{
defaultInput.Disable();
}
void Update()
{
if (defaultInput.Character.Pause.triggered)
{
gameObject.GetComponent<Character_Control>().enabled = !gameObject.GetComponent<Character_Control>().enabled;
}
}
}
I start the game with the "Character_Control" script enabled, and when I press escape (opening the pause menu), I can still control my character, but when I press escape for the second time (closing the pause menu), I cannot control my character, meaning the "Character_Control" script is disabled. Obviously I want the opposite to happen, so the "Character_Control" is disabled during pause.
Here is a video of my problem: https://drive.google.com/file/d/1hmtdMYcvW5tKhdBiCs-XklRZ75vpu81s/view?usp=sharing
Answer by andrew-lukasik · Jan 02 at 09:27 PM
Try:
using UnityEngine;
public class ToggleComponentWithInputSystem : MonoBehaviour
{
[SerializeField] Character_Control _target = null;
DefaultInput _controls;
void OnEnable ()
{
_controls = new DefaultInput();
_controls.Character.Pause.performed += (ctx) => _target.enabled = !_target.enabled;
_controls.Character.Pause.Enable();
_target.enabled = true;
}
void OnDisable () => _controls.Dispose();
}
Tried it, attached the CharacterControl Script and I still have the same problem...
That's ok. You can fix this with event then - I don't mean input events but:
public event System.Action OnPaused;
public event System.Action OnUnpaused;
to which your script could subscribe to be notified when game became paused/unpaused so there zero confusion about that in the code.
Your answer
Follow this Question
Related Questions
I need Function to be in other script 1 Answer
Physics2D.OverlapCircle working in Unity but not in build 0 Answers
Get color from ColorPicker and apply it randomly on GameObject 0 Answers
How can I make a float decrease when touched by a cube? 0 Answers
How do I assign values to variables in the Update function only ONCE? 1 Answer