Accessing an Array element from a non-Array Class

Sorry to those who have replied - I don’t have enough rep yet to reply directly. If you see this, I have added the trimmed-down original code to the bottom.

Hi, I’m new to Unity and learning as I go, so sorry for the noob question. I have searched online for this but can’t find a solution and it’s bugging me as it seems logical in my head. I’m trying to access arrays that are assigned to Class instances. e.g.

Int newInt = ClassMember.numberArray[0];

// An array type variable is declared as numberArray in the class and has been assigned to this member from a choice of Arrays declared elsewhere (ClassMember.numberArray = intArray1; ) which contains int values. I would expect this to set newInt as the first number in intArray1 accessed via NumberArray, but it displays this error:

     CS0021 Cannot apply indexing with [] to an expression of type 'Array'

Can someone please explain why this doesn’t work in C# and what alternative I could use to access array elements from classes? Many thanks.

As this may be more complex than I anticipated, here is the original code extracted/trimmed down from a much larger script:

// Setup
class GamePiece {
Array opponentArray;
}

GamePiece P1 = new GamePiece(); // Player pieces
GamePiece P2 = new GamePiece();
GamePiece E1 = new GamePiece(); // Enemy pieces
GamePiece E2 = new GamePiece();

GamePiece playerPieceArray;
GamePiece enemyPieceArray;

P1.opponentArray = enemyPieceArray;
P2.opponentArray = enemyPieceArray;
E1.opponentArray = playerPieceArray;
E2.opponentArray = playerPieceArray;

playerPieceArray = new GamePiece { P1, P2 };
enemyPieceArray = new GamePiece { E1, E2 };

// Game
// Set piece to move
GamePiece activePiece = P1;
// Set piece to attack
GamePiece targetPiece = activePiece.opponentArray[0]; // targetPiece = E1 (?)
// Returns error

Hi,

I am not sure without your source code. But I think the reason is The Array class has not indexers. You can try:

int newInt = ClassMember.numberArray.GetValue(0);

or
use List<T> instead of Array.

You haven’t shown your code and how you declared your array variable. Usually an array with integer values is declared as

public int[] numberArray;

You probably did not. Maybe you tried to use the System.Array class which is just an abstract base class for array types and in almost all cases you don’t want to mess with that. However your error seems to indicate that you created your own class which you called “Array”. However all that we have to read between the lines as you shared none of your relevant code.