问题
I'm running into trouble with my RemoveTail function which executes the code: destroy(gameObject). This snake game creates a clone of the my Snake prefab and I control the Snake's length by assigning a "tail" and deleting the "tail" gameobject if maxSize is reached. I understand that my error is due to the game deleting my tail which is a clone of the prefab instead of deleting an instance of Snake. Any ideas or suggestions on how I may resole this issue?
Snake script
public class Snake : MonoBehaviour {
private Snake next;
public Snake GetNext() {
return next;
}
public void SetNext(Snake IN) {
next = IN;
}
public void RemoveTail() { // This method destroys the gameObject assigned as tail
Destroy(gameObject);
}
public static Action<string> hit;
public void OnTriggerEnter(Collider other) {
if (hit != null)
hit(other.tag);
if (other.tag == "Food")
Destroy(other.gameObject);
}
}
Excerpt from my GameController script
void TailFunction() {
Snake tempSnake = tail; // Create a temp Snake variable to store tail information
tail = tail.GetNext(); // Now that we have a copy of original tail in tempSnake, we set the next Snake gameobject as our new tail
tempSnake.RemoveTail(); // Remove the original tail gameObject
}
void Movement() {
GameObject temp;
nextPos = head.transform.position;
switch (direction) {
case Direction.North:
nextPos = new Vector2(nextPos.x, nextPos.y+1);
break;
case Direction.East:
nextPos = new Vector2(nextPos.x+1, nextPos.y);
break;
case Direction.South:
nextPos = new Vector2(nextPos.x, nextPos.y-1);
break;
case Direction.West:
nextPos = new Vector2(nextPos.x-1, nextPos.y);
break;
}
temp = (GameObject)Instantiate(snakePrefab, nextPos, transform.rotation);
head.SetNext(temp.GetComponent<Snake>());
head = temp.GetComponent<Snake>();
return;
}
void TimerInvoke() {
Movement();
if (currentSize == maxSize)
TailFunction();
else
currentSize++;
}
回答1:
My problem was I dragged my prefab into my inspector and deleted my original snake cube. Instead of assigning my original snake cube as tail when the game began and then deleting the gameobject, my program was assigning my actual prefab as the tail and attempting to delete the prefab outright.
来源:https://stackoverflow.com/questions/43973360/destroying-assets-is-not-permitted-to-avoid-data-loss