unitytips: Indices
08/12/2020
Unity started to supporting C# 8.0 with version 2020.2 beta and now we can start to use some new features like the Indices.
Introduction
Indices provide a succinct syntax for accessing single elements in array/collection.
Consider the array below:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var words = new string[] | |
{ | |
// index from start index from end | |
"The", // 0 ^9 | |
"quick", // 1 ^8 | |
"brown", // 2 ^7 | |
"fox", // 3 ^6 | |
"jumped", // 4 ^5 | |
"over", // 5 ^4 | |
"the", // 6 ^3 | |
"lazy", // 7 ^2 | |
"dog" // 8 ^1 | |
}; // 9 (or words.Length) ^0 | |
var allWords = words[..]; // contains "The" through "dog". | |
var firstPhrase = words[..4]; // contains "The" through "fox" | |
var lastPhrase = words[6..]; // contains "the", "lazy" and "dog" |
- The 0 index is the same as sequence[0].
- The ^0 index is the same as sequence[sequence.Length].
Note that sequence[^0] does throw an exception, just as sequence[sequence.Length] does. For any number n, the index ^n is the same as sequence.Length - n.
Loading comments...