In our game, player should shoot objects in a correct order.
I mean, he/she has to shoot ObjectA first.
If he/she shoots ObjectA first, game continues, else game over.
After shooting ObjectA, player needs to shoot Object B.
It goes like that.
I tried to solved it like that but this one didnt work.
If player shoots the Object with Tag ‘x’, it directly goes to else function and stops the time.
insert the game objects in order into the array (in the reverse order you expect to shoot them)
when the player shoot, check the array’s last element, if it’s the correct object, remove it from the array (or alternatively you can use an index variable, whatever works for you)
if the two objects aren’t matching, you know that the player shot something else, so you can game over
if the array becomes empty (or the index variable becomes zero), all the game objects was shot
I got the idea but, when I tried it, this won’t help me.
Can’t I do just like if else statement?
Maybe like, if gameobject collide with correct tag first, then continue to try to hit the other object.
Or in this case, if else’s are just not good enough to solve this issue?
What I would likely do is have a list of targets in the order they should be hit and then simply check if the object hit was first in the list and remove it. Once the list is empty, all the targets have been hit in order.
using System.Collections.Generic;
using UnityEngine;
public class TargetChecker
{
private List<GameObject> _targets;
//Assign targets to the list in the order they need to be hit
public void AssignTargets(List<GameObject> targets)
{
_targets = new List<GameObject>(targets);
}
public void CheckTarget(GameObject hitObject)
{
if(hitObject == _targets[0])
{
_targets.RemoveAt(0);
if(_targets.Count <= 0)
{
//All targets hit, deal with that.
}
}
else if(_targets.Contains(hitObject))
{
//An object was shot out of order
//Code to deal with that
}
else
{
//An object not in the list was hit
//Code to deal with that
}
}
}
If it’s too much, my apologizes.
But may I ask you one more thing?
How can I transform your script onto Collider2d and without destroying the object hit?
I mean, object hit the targets[0] then skip to targets[1] then 2 then 3.