- Home /
Can't set object position, help!
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!
$$anonymous$$aybe the problem comes from how you call "switchToNext". Do you call it from the Update method when the user hits the tab button ?
Did you check the length of targets ?
Where are you checking for the tab key being pressed and calling switchToNext() ?
Answer by Simo Iliev · May 06, 2014 at 02:06 PM
Hmm I found that linking the input controller to the crosshair prefab is the reason for this behaviour. I've now linked them through tagging, and that solved the problem!
Your answer
Follow this Question
Related Questions
Shoot second cell in 2d 0 Answers
How To Create 2D Arrays 1 Answer
How to make race positioning system work for more than two racers 1 Answer
Setting children position to Vector3.zero doesn't make them go to center of parent? 1 Answer
[C#] Check position of multiple GameObjects with mouse click position 0 Answers