I’m making a targeting system for a 2D game, and i need my crosshair to iterate between an array of possible targets by hitting the TAB key (starting switchToNext() function ). The following code should be doing just that:
GameObject[] targets;
private int curPos = 0;
void Start () {
targets = GameObject.FindGameObjectsWithTag ("PotentialTarget");
}
void LateUpdate () {
gameObject.transform.position = targets [curPos].transform.position;
}
public void switchToNext()
{
targets = GameObject.FindGameObjectsWithTag ("PotentialTarget");
curPos += 1;
if(curPos >= targets.Length)curPos = 0;
Debug.Log (curPos + " X: " + targets[curPos].transform.position.x + " Y: " + targets[curPos].transform.position.y);
}
The debug log shows correct values, but setting the crosshair position to them doesn’t work. Actually, the crosshair jumps from its origin to the first game object position at the start of the game, but fails to iterate through others for some unknown reason! I am really confused about this behaviour. Any help will be greatly appreciated!