Главная | Обратная связь | Поможем написать вашу работу!
МегаЛекции

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:
using System. IO;

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 filePath = Application. dataPath + " /";

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:
private class SaveObject {
public int score;
}

Instantiate to save: When you save, instantiate an instance of the class and populate its fields by invoking a constructor:
int gameScore = 5;
SaveObject saveObject = new SaveObject {
score = gameScore,
};

Call the JsonUtility: This will create a string formatted according to the JSON standard:
string json = JsonUtility. ToJson(saveObject);

Save: The string can be saved with the following method call:
File. WriteAllText(filePath + saveFileName, json);

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:
if (File. Exists(filePath + saveFileName)) {

          

}

Loading: Data is loaded from the file in a string format:
string json = File. ReadAllText(filePath + saveFileName);

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:
int gameScore = saveObject. score;

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:
public string filePath = Application. dataPath + " /Saves/";

Then, in Awake:
private void 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
if (Input. GetKeyDown(KeyCode. R)) {

 

}

Key Release: Returns true on the frame a key is released
if (Input. GetKeyUp(KeyCode. R)) {

 

}

Key Held: Returns true while the key is held
if (Input. GetKey(KeyCode. R)) {

 

}

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
if (Input. GetMouseButtonDown(0)) {

 

}

Mouse Release: Returns true on the frame a key is released
if (Input. GetMouseButtonUp(0)) {

 

}

Mouse Held: Returns true while the key is held
if (Input. GetMouseButton(0)) {

 

}

ScrollWheel:
if (Input. mouseScrollDelta. y > 0f) { //Forward

//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
https: //www. youtube. com/watch? v=Pzd8NhcRzVo

Brackeys Controller Input: Look at usage of Input System in the context of using a Controller
https: //www. youtube. com/watch? v=p-3S73MaDP8& t=81s

Unity Introduction of new Input System: Official video documentation
https: //www. youtube. com/watch? v=hw3Gk5PoZ6A

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:
using UnityEngine. InputSystem;

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:
private Keyboard kb;

■ 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:
kb = InputSystem. GetDevice< Keyboard> ();

■ Assign a reference to the device, matching the type declared in the Class

○ In Update / FixedUpdate (wherever you need to make the query):
if (kb. spaceKey. wasPressedThisFrame)

   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:
private SimpleControls m_Controls;

■ “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.
public void Awake() {

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:
public void OnEnable() {

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_Controls. gameplay. fire. canceled += ctx =>

{

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:
m_Controls. gameplay. fire. performed += ctx => Fire();

● 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:
private Vector2 moveVector;
...
m_Controls. gameplay. move. performed += ctx => moveVector = ctx. ReadValue< Vector2> ();

● 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:
m_Controls. gameplay. move. performed += ctx => Move(ctx. ReadValue< Vector2> ());

● 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:
public void Update() {

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;
private void ButterflyMove(InputAction. CallbackContext context) {

   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:
using UnityEngine. InputSystem;

■ To make use of input “phases” (Performed, Started, Cancelled) you will need an additional using directive:
using UnityEngine. InputSystem. Interactions;

○ 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.
private Vector2 m_Move;

■ 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:
public void OnMove(InputAction. CallbackContext context) {

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.
public void Update() {

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;
https: //docs. unity3d. com/Packages/com. unity. inputsystem@0. 1/api/UnityEngine. Experimental. Input. InputActionPhase. html

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 - 2024 megalektsii.ru Все авторские права принадлежат авторам лекционных материалов. Обратная связь с нами...