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