问题描述
我的 RemoveTail 函数遇到了问题,该函数执行代码:destroy(gameObject).这个蛇游戏创建了我的 Snake 预制件的克隆,我通过分配尾巴"并在达到 maxSize 时删除尾巴"游戏对象来控制 Snake 的长度.我知道我的错误是由于游戏删除了我的尾巴,它是预制件的克隆,而不是删除了 Snake 的实例.关于我如何解决此问题的任何想法或建议?
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?
蛇脚本
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);
}
}
摘自我的 GameController 脚本
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++;
}
推荐答案
我的问题是我将我的预制件拖到我的检查器中并删除了我原来的蛇形立方体.我的程序没有在游戏开始时将我的原始蛇立方体指定为尾部然后删除游戏对象,而是将我的实际预制件指定为尾部并尝试彻底删除预制件.
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.
这篇关于不允许破坏资产以避免数据丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!