I feel like it may be a quick fix or something, and sometimes it works normally but 80% of the time it infinitely spawns a tail whenever it eats the food. I have another food script that spawns the food in and that works fine but the problem comes whenever the snake eats the first piece of food and the tail keeps growing. I don’t even know if I am putting my code in right but any help would be appreciated thank you!
public class Snake : MonoBehaviour {
//Game Over Text
public TextMeshProUGUI gameOverText;
//Manages the Tail
List <Transform> tail = new List<Transform>();
// Tail Prefab
public GameObject tailPrefab;
public bool isGameActive=true;
// snake moving to the right by default
public Vector2 dir = Vector2.right;
// Did the snake eat something?
public bool ate = false;
void Start() {
// Move the Snake every 100ms
InvokeRepeating("Move", 0.1f, 0.1f);
}
// Update is called once per frame
void Update() {
// Move snake in a new direction
if (Input.GetKey(KeyCode.RightArrow))
dir = Vector2.right;
else if (Input.GetKey(KeyCode.DownArrow))
dir = -Vector2.up;
else if (Input.GetKey(KeyCode.LeftArrow))
dir = -Vector2.right;
else if (Input.GetKey(KeyCode.UpArrow))
dir = Vector2.up;
}
void Move() {
if (isGameActive){
// Save current position of the snake
Vector2 v = transform.position;
// Move the snake's head
transform.Translate(dir);
// Ate something? Then insert new Element into gap
if (ate) {
// Load the next part of the tail into the world
GameObject g =((GameObject)Instantiate(tailPrefab, v, Quaternion.identity));
// Reset the snake so it is no longer eating anything
ate = false;
// put it in the tail list
tail.Insert(0, g.transform);
}
//adds new game object on the end
else if (tail.Count > 0) {
// Move last Tail Element to where the Head was
tail.Last().position = v;
// Add to front of list, remove from the back
tail.Insert(0, tail.Last());
tail.RemoveAt(tail.Count-1);
}
}
}
void OnTriggerEnter2D(Collider2D coll) {
// when it collides with food
if (coll.name.StartsWith("food prefab(Clone)")) {
// Get longer in next Move call
ate = true;
// get rid of the food
Destroy(coll.gameObject);
}
// Collided with Tail or Border
else if(coll.name.StartsWith("BorderLeft")){
gameOverText.gameObject.SetActive(true);
isGameActive=false;
}
}
}