Using JSON. General. Legacy Input Manager. Keyboard. Right-Click. New Input System
Using JSON ● Reference: Simple Saving and Loading with JSON to a File (Unity Tutorial for Beginners) - YouTube ● Using Directive: To read from / write to a file, include: ● Create a save path and file name: Create strings which hold the location all data should be saved to / loaded from, and the file to write to: public string saveFileName = " save. txt"; ○ Application. dataPath: This will save to the Unity Asset folder Saving: ● Create a class which holds all save data: Create a private class (which does not inherit from Monobehaviour) which will hold all the data you wish to save: ● Instantiate to save: When you save, instantiate an instance of the class and populate its fields by invoking a constructor: ● Call the JsonUtility: This will create a string formatted according to the JSON standard: ● Save: The string can be saved with the following method call: ○ Append the file name to the path: The “filePath” + “saveFileName” strings are added together to produce a complete file path. The string “json” is saved to into this location / file. Loading: ● Check if the file exists: Before trying to read from a file which doesn’t exist, perform the following check:
} ● Loading: Data is loaded from the file in a string format: ● Parsing the loaded String: To parse the string read from the file, declare another instance of the SaveObject which will receive data from the JsonUtility: SaveObject saveObject = JsonUtility. FromJson< SaveObject> (json); ○ Note that the Type “SaveObject” is supplied to the generic “FromJson” method so it knows how to parse the data in the string “json” ● Pull data from the loaded object: Lastly, read data from the SaveObject: Creating a Directory: ● Create a Folder for saves: Instead of saving directly into the Application dataPath, you can create a sub-directory to save into, and ensure that it is created if it does not exist with the following code: ○ Then, in Awake: if (! Directory. Exists(filePath)) { Directory. CreateDirectory(filePath); } } Input General ● Input should be handled in Update: Calls to Input should be made from within the Update Method ○ Move in FixedUpdate: The application of movement (in fact, any sort of physics calculation) should be done in FixedUpdate which is called a fixed number of times depending on your game’s framerate.
● Input Handling: ○ Input. GetAxisRaw: Returns a range from -1 to 1 on either the “Horizontal” or “Vertical” axis. Legacy Input Manager Keyboard ● KeyCode: An Enum with a list of the String References for each common key on the keyboard ● Key Press: Returns true on the frame a key is pressed
} ● Key Release: Returns true on the frame a key is released
} ● Key Held: Returns true while the key is held
} Mouse ● Mouse Buttons: Mouse Buttons are specified with Integer reference; ○ Left: 0 ○ Right: 1 ○ Middle: 2 ○ Etc. ● Mouse Press: Returns true on the frame a key is pressed
} ● Mouse Release: Returns true on the frame a key is released
} ● Mouse Held: Returns true while the key is held
} ● ScrollWheel: //Debug. Log(" ScrollDelta: " + Input. mouseScrollDelta. y); } else if (Input. mouseScrollDelta. y < 0f) { //Backwards //Debug. Log(" ScrollDelta: " + Input. mouseScrollDelta. y); } ● _ Right-Click public void OnPointerClick (PointerEventData evd) { if (evd. button == PointerEventData. InputButton. Right) { Debug. Log (" Right Mouse Button Clicked on: " + name); } } New Input System ● Reference: ○ Brackeys New Input System: Somewhat outdated look at the setup of the input system ○ Brackeys Controller Input: Look at usage of Input System in the context of using a Controller ○ Unity Introduction of new Input System: Official video documentation ○ Unity Documentation; Input System | Input System | 1. 0. 0-preview. 6 ● Namespace Setup: To use the new Input System in a Class, you must include the following using directive: ● Direct Input Query: This is the fastest way (using the new Input system) to query a specific key (this is NOT the official name for this) ○ Usage: Prototyping / Debugging (you probably want to use a more elaborate version of the system for production code) ○ In the Class: ■ Declare a private variable of the type of input system you wish to query, in this case “Keyboard”, named “kb” for short. ○ In Start / Awake: ■ Assign a reference to the device, matching the type declared in the Class ○ In Update / FixedUpdate (wherever you need to make the query): Debug. Log(" Spacebar Pressed" );
■ Checks if the spaceKey was pressed this frame ● Using Action set Asset: The more elaborate way of handling input. ○ Create the Action Set Asset: (Watch Brackeys video for how to do this) ○ Generate a C# wrapper class: This will be generated with the name of the Action Set Asset; this name will be used in all Script references ○ In the Class: Create a reference to the input asset class: ■ “SimpleControls” is the name of the asset in the Unity demo ■ m_Controls is the name of the variable ○ On Awake: new-up an instance of the control class. m_Controls = new SimpleControls(); ○ Enabling / Disabling input Actions: Input Actions must be enabled / disabled in the OnEnable / OnDisable methods, using the reference set up in the Class and defined in OnAwake: m_Controls. Enable(); }
public void OnDisable() { m_Controls. Disable(); } ■ Simply call “Enable()” within the OnEnable method, and “Disable()” in the OnDisable method. ○ Set up Event Handlers: Each input event can be wired up with an anonymous delegate in OnAwake through the use of a Lambda expression, or you can have each event point to a method somewhere in the class: ■ Anonymous method: { m_Charging = false; }; ● Here, when the “fire” input is “cancelled” it sets “m_Charging” to false, not making use of the “ctx” Context data ■ Defined Method: ● Here, when the “fire” input is “performed” it triggers the “Fire()” method which should be defined elsewhere in the class, again, not making use of the “ctx” Context data ■ Assign a value: ● Here, when the “move” input is “performed” it reads a Vector2 from the context Data and assigns that value to moveVector which can be used elsewhere in the Class. ■ Pass a Value to a Defined Method: ● Here, when the “move” input is “performed” it calls the Move method, which expects a Vector2, provided by reading from the Context Data ○ Checking input in Update: As an alternative to “Assign a value” (above), you can also ReadValue in Update, as in the following example: var move = m_Controls. gameplay. move. ReadValue< Vector2> (); Move(move); } ■ This negates the necessity of using the Lambda expression in the Awake method. ■ An Event with (functionally) the same code; rStick = context. ReadValue< Vector2> (); Debug. Log(" rStick: " +rStick); } ○ ● PlayerInput: An automated way of disseminating control input from multiple players (devices) and switching between devices (gamepad / keyboard / etc. ) ○ Actions: The reference to the Action Set Asset ○ Behaviour: How the PlayerInput will send events to actually trigger things in your application ○ Namespace Setup: ■ For basic Unity Events, include: ■ To make use of input “phases” (Performed, Started, Cancelled) you will need an additional using directive: ○ https: //docs. unity3d. com/Packages/com. unity. inputsystem@0. 1/api/UnityEngine. Experimental. Input. InputActionPhase. html ■ These “phases” do not correspond directly to “pressed” / “released” etc, in particular, the ones in this example are related to the “Slow Tap” input option
○ Creating Unity Events: ■ In the Class: For situations like movement (or looking around) which can make use of a Vector2, you can create a class-level variable which will be updated by the actual Events. ■ Input Events: You will hook into these Events from the Inspector via the traditional Unity Events interface. Each Event provides “context” data which can be read from inside the method via the “context” parameter: m_Move = context. ReadValue< Vector2> (); } ● Each input Event method is public, void ● It should have “InputAction. CallbackContext context” as its parameter, although “context” can be substituted for a different name (like ctx for short) ■ Perform logic operations on input data: Using the data set in the Input Event, you can call a separate (private) method elsewhere in the class from within Update providing the data as a parameter. Move(m_Move); } ■ Call Methods directly from Input Events: Other types of input can be handled immediately without being called from within Update, and may not use Context data, or they may use the Context data to perform different actions based on the context “phase” ■ public void OnFire(InputAction. CallbackContext context) { switch (context. phase) { case InputActionPhase. Performed: if (context. interaction is SlowTapInteraction) { StartCoroutine(BurstFire((int)(context. duration * burstSpeed))); } else { Fire(); } m_Charging = false; break;
case InputActionPhase. Started: if (context. interaction is SlowTapInteraction) m_Charging = true; break;
case InputActionPhase. Canceled: m_Charging = false; break; } } ■ Switch(context. phase): Evaluates which “phase” the SlowTap is in; ■ context. interaction verifies if the input met the conditions of a “Slow Tap” in which case this example initiates a coroutine. If it fails to meet this condition, the “Fire()” method is invoked instead. ■ Context. duration tracks how long the key was held for (documentation is sparse on this, inferred from context).
Воспользуйтесь поиском по сайту: ![]() ©2015 - 2025 megalektsii.ru Все авторские права принадлежат авторам лекционных материалов. Обратная связь с нами...
|