Hello, I’m quite new to c# and I’m looking at someone else’s script (included below), which seems to provide a way to switch between different controller setups.
I understand most of this, but I’m confused by the use of “var”, for example
foreach (var mode in this.ControlModes) {
if (mode != this.currentMode) {
mode.Behaviour.enabled = false;
}
If I hover the mouse-over “var” in visual studio, a box comes up telling me that “var” is of type “ControlModeSwitcher.ControlMode”, but how does the script know what type this “var” should be? Is it just inferred from the rest of the line, i.e. if a var is in the ControlModes array, it must be a ControlMode?
Does this syntax only work within a “foreach” loop, or can it be used elsewhere?
Is there any reason to use “var” here, rather than:
foreach (ControlMode mode in this.ControlModes) {
if (mode != this.currentMode) {
mode.Behaviour.enabled = false;
}
}
using UnityEngine;
using System.Linq;
using System;
public class ControlModeSwitcher : MonoBehaviour {
[System.Serializable]
public class ControlMode {
public KeyCode KeyCode;
public MonoBehaviour Behaviour;
}
public ControlMode[] ControlModes;
public KeyCode[] ModeSwitchKeys;
private ControlMode currentMode;
void Start() {
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
if (this.ControlModes.Any()) {
this.SetMode(this.ControlModes[0]);
}
foreach (var mode in this.ControlModes) {
if (mode != this.currentMode) {
mode.Behaviour.enabled = false;
}
}
}
void Update() {
foreach (var mode in this.ControlModes) {
if (Input.GetKeyDown(mode.KeyCode)) {
this.SetMode(mode);
}
}
if (this.currentMode != null && this.ModeSwitchKeys != null) {
foreach (var keyCode in this.ModeSwitchKeys) {
if (Input.GetKeyDown(keyCode)) {
int currentIndex = Array.IndexOf(this.ControlModes, this.currentMode);
this.SetMode(this.ControlModes[(currentIndex + 1) % this.ControlModes.Length]);
}
}
}
}
void SetMode(ControlMode mode) {
if (this.currentMode == mode) {
return;
}
if (this.currentMode != null) {
this.currentMode.Behaviour.enabled = false;
}
this.currentMode = mode;
this.currentMode.Behaviour.enabled = true;
}
}
