0
\$\begingroup\$

So in Unity I'm making Snake, and to do that I've a list which houses all the tail elements from the Snake (this was implemented by the NoobTuts tutorial on snake just FYI).

I'm find with adding stuff and removing stuff from the list, HOWEVER, I do have an issue with part of the removal.

When I remove an object from the list it's still in the scene, it's just not acting with the rest of the objects still in the list. All I need to do, is just destroy that object.

I'm not sure if you can destroy an object in a list, or if that'll cause an issue, so I've been trying to set a gameobject to the value at the end of the list. However all list methods seem to just return the bloody index value, not the value in the index!

I've had a look through MSDN but can't understand parts of it.

Here's what I have:

else if (ateslow)
    {
        tailExcess = tail.Count - 1;

        //tail.IndexOf(tail.Count - 1);
        tail.RemoveAt(tail.Count-1);
        ateslow = false;
        if (snakeSpeed < minSnakeSpeed)
            snakeSpeed += 0.0f;
    }

So I play on having tailExcess equal the last element in the list, then I plan on destroying tailExcess after having it popped from the list. The rest below that doesn't matter.

What am I missing?

\$\endgroup\$
  • \$\begingroup\$ list[index] to get the item in the list at that index. \$\endgroup\$ – milk Aug 1 '16 at 19:32
  • \$\begingroup\$ I feel like a muppet, but thank you! I've just never used lists so I've no idea what I can and can't do with them. Cheers though seriously. If you want to post that as an answer so I can select it as the right solution to give you some rep and tie this up :) \$\endgroup\$ – Bearzerk Aug 1 '16 at 19:40
  • \$\begingroup\$ I wasn't sure if you also needed help with destroying the object once you've got the reference. Since it looks like you don't, made an answer. \$\endgroup\$ – milk Aug 1 '16 at 19:51
  • \$\begingroup\$ Yea no, I'm fine with the Destroy() method, I just wanted a Snake game varient where you can eat food to make you bigger and faster and therefore make it dangerous, and another food to make it smaller and slower to be a safe bet. It works, just looks slightly odd how the entire creature changes length. \$\endgroup\$ – Bearzerk Aug 1 '16 at 19:56
0
\$\begingroup\$

Lists in C# support lookup by indexing (like with arrays). In MSDN documentation on the indexing is typically under a property called Item[<.index type>].

So you can get items in a list by index like this:

var lastIndex = tail.Count - 1;
var tailExcess = tail[lastIndex];
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.