- Home /
Using an int to find the index of a GameObject array
Sorry if I format anything wrong but let me start out by saying, I am very new to arrays and I cant seem to find this answer put simply anywhere, so I have this code for a piece to move around a board game, there is a GameObject array that I intend to use as anchors to translate the players to depending on what they roll, which is int x, they will then have an offset applied to them depending if the space is occupied or not. Now that's all fine and dandy but I have no clue how to use the playerpos int + x to find a specific GameObject in the array to translate the player to. So lets say the player is on the first square and rolls a 6, he will be on the 7th square which should be the 6th object in the array, so the code should essentially take the playerpos + x(the rolled number) and get the 6th GameObject in the array, then translate the player over to said object. Any ideas? And a simple explanation would be nice!
public class move : MonoBehaviour
{
public GameObject[] anchor = new GameObject[20];
public int playerpos;
private void Start()
{
playerpos = 0;
}
public void MovePlayer(int x)
{
playerpos += x;
if (playerpos > 19)
{
playerpos = 0;
}
Debug.Log(x);
}
}
Answer by unity_ek98vnTRplGj8Q · Jul 21, 2020 at 07:39 PM
I assume you are just asking how to use the int as an index? I'm assuming you already have the array populated with all of the board spaces
public void MovePlayer (int x) {
playerpos += x;
if (playerpos > 19) {
playerpos = playerPos - 20;
}
Gameobject destanationObject = anchor[playerPos];
//Now you can move the player there
//Assuming this script as attached to your player
transform.position = destanationObject.transform.position;
Debug.Log (x);
}