- Home /
Removing segments
I working on a snake-esque game in which I'm trying to make it so that when the snake head collides with a segment, that segment and all the segments behind it will be destroyed. In their scripts(all the same), all the segments have a variable (segmentNum) which is their number in the snake. How would I go about finding all the segments with their segmentNum being greater than the collision GO, finding out how many of those there are, and also accessing them through the head behavior script so I can delete them? Thank you so much in advance
Answer by robertbu · Aug 14, 2013 at 07:07 PM
The typical way to solve this problem is to use a linked list. Let's say each segment has its own script called 'Segment'. At the top the Segment script would have:
var tailSegment : Segment;
Each time you add a new segment, the previous end segment has it 'tailSegment' variable to the new end segment. Then you would have a 'Delete()' function:
function Delete() {
if (tailSegment != null)
tailSegment.Delete();
Destory(gameObject);
}
You call this function on the segment hit, and it will destroy the entire tail.
Another way is to use a more global approach. Tag all your segments with the same tag. Then you can do:
var gos = GameObject.FindGameObjectWithTag("Segment");
for (var go : GameObject in gos) {
var seg : Segment = go.GetComponent(Segment);
if (seg.id > some_value)
Destroy(go);
}
Your answer
Follow this Question
Related Questions
Get the number of items for loop returns 1 Answer
Setting Scroll View Width GUILayout 1 Answer
JS Setting int value from another script 1 Answer
FPS Game Muzzle Flash 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers