简体   繁体   English

Unity Destroy 和其他代码不起作用?

[英]Unity Destroy and other code not working?

I'm trying to make the game Snake, and I'm trying to get the apple functionality working.我正在尝试制作 Snake 游戏,并且正在尝试让苹果功能正常工作。 What this script is meant to do, is whenever my Snake goes over the Apple, the apple disappears and reappears at a random location on the screen.这个脚本的目的是,每当我的蛇越过苹果时,苹果就会消失并重新出现在屏幕上的随机位置。 But instead it does nothing, any idea as to why?但相反,它什么也不做,知道为什么吗?

PS: Camera is Size 10 and Aspect Ratio is 16:9 which is why I have some weird Random.Range values. PS:相机尺寸为 10,纵横比为 16:9,这就是为什么我有一些奇怪的 Random.Range 值。 Also I used Debug.Log in Update to make sure that the variable worked, and yes it does, whenever my snake moves its coordinates are displayed.此外,我在 Update 中使用 Debug.Log 来确保变量有效,是的,每当我的蛇移动时,它的坐标就会显示出来。

public class Apple_RandomSpawn : MonoBehaviour
{
    private Vector2 foodPos;
    private Snake_Move snakeMove;

    void Start()
    {
        SpawnApple();
    }

    public void Update()
    {
        transform.position = new Vector2(foodPos.x, foodPos.y);
        SnakeAte();
    }

    public void SpawnApple()
    {
        foodPos = new Vector2(Random.Range(-17, 17), Random.Range(-9, 9));
    }

    public void SnakeAte()
    {
        if (Mathf.Approximately(foodPos.x, snakeMove.pos.x) && Mathf.Approximately(foodPos.y, snakeMove.pos.y))
        {
            SpawnApple();
        }
    }
}

First of all, it does not directly have something to do with your problem, but DO NOT put GetComponent() or GameObject.Find() in the Update() function.首先,它与您的问题没有直接关系,但不要将GetComponent()或 GameObject.Find( GameObject.Find()放在Update() function 中。 These two, especially GameObject.Find() function is super heavy , so It's recommended that you should call these kinds of function inside Start() or Awake() , or at the initiallization of a class.这两个,尤其是 GameObject.Find GameObject.Find() function 是超重的,所以建议你应该在Start()Awake()中调用这几种 function ,或者在 ZA42F2ED4F8EBC02A 初始化时调用 function It can directly, and heavily impact the performance of your game, so here's my suggestion:它可以直接并严重影响游戏的性能,所以这是我的建议:

[SerializeField]
private Snake_Move snakeMove;

And drag your gameobject (which Snake_Head component is attatched) via Inspector.并通过 Inspector 拖动您的游戏对象(附加了Snake_Head组件)。 You should always consider this way first, rather than using GameObject.Find() and GetComponent() .您应该始终首先考虑这种方式,而不是使用 GameObject.Find( GameObject.Find()GetComponent()

Second, Float is not recommend to compare equality directly through = , since there must be rounding error .其次,不建议Float直接通过=比较相等,因为肯定有舍入误差 There is a help function with regard to comparing two float value in Unity, like Mathf.Approximately(float a, float b) .关于比较 Unity 中的两个浮点值,有一个帮助 function,例如Mathf.Approximately(float a, float b) Directly comparing two float value via = would almost always not work as you might think.通过=直接比较两个float值几乎总是不会像您想象的那样工作。

Third, It doesn't seem to be that there are no Instantiate() function in your code, but you are try to use one apple object, and every time you consume it, just change it's position.第三,您的代码中似乎没有Instantiate() function,但是您尝试使用一个苹果 object,并且每次使用它时,只需将其更改为 Z4757FE07FD492A8BE0EAZ.8A760DE Then why does Object.Destroy(gameObject) exists?那为什么Object.Destroy(gameObject)存在呢? What you're doing is, just destroying the apple when you get it first time.你正在做的是,当你第一次得到它时就摧毁它。 I think you have to remove the Destroy() function, and SpawnApple() changes the target coordinate of apple, and the position will be updated in Update() function.我认为你必须删除Destroy() function, SpawnApple()更改苹果的目标坐标,position 将在Update() ZC1C425268E68385D14AB5074C17Z9 中更新。

And it's no need to indirectly set the target position, and update to it in Update() function.并且不需要间接设置目标 position,并在Update() function 中对其进行更新。 You can directly set the position of apple, like:可以直接设置apple的position,如:

// assuming you followed my suggestio aboven about snakeMove.

public void Update()
    {
        SnakeAte();

        Debug.Log(snakeMove.pos);
    }

public void SpawnApple()
    {
        transform.position = new Vector2(Random.Range(-17, 17), Random.Range(-9, 9));
    }

public void SnakeAte()
    {
        if (foodPos == snakeMove.pos)
        {
            SpawnApple();
        }
    }

First of all your null ref in your last comment comes from: private Snake_Move snakeMove;首先,您最后一条评论中的 null 参考来自: private Snake_Move snakeMove; Its a private variable and its never assigned.它是一个私有变量,并且从未分配过。 You either need to make it public/[SerialistField] and assign it in inspect or have some sort of initialize function that give it a value.您要么需要将其设为 public/[SerialistField] 并在检查中分配它,要么有某种初始化 function 给它一个值。

For the hit detection Mathf.Approximately is good if you wan to check if 2 floats are exactly the same.对于命中检测,如果您想检查 2 个浮点数是否完全相同,Mathf.Approximately 会很好。 If you'r checking 2 positions of moving objects the chance of them being exactly the same is very low and may rely on frame rate and such.如果您正在检查移动物体的 2 个位置,那么它们完全相同的机会非常低,并且可能取决于帧速率等。 Keeping your implementation you can check instead for a minimum distance between the 2 positions.保持您的实施,您可以检查两个位置之间的最小距离。 You can tweak DISTANCE_THRESHOLD for a value that suits your better.您可以调整 DISTANCE_THRESHOLD 以获得更适合您的值。

public class Apple_RandomSpawn : MonoBehaviour
        {
            private const float DISTANCE_THRESHOLD = 0.1f;
            private Vector2 foodPos;
            private Snake_Move snakeMove;

            void Start()
            {
                SpawnApple();
            }

            public void Update()
            {                   
                SnakeAte();
            }

            public void SpawnApple()
            {
                foodPos = new Vector2(Random.Range(-17, 17), Random.Range(-9, 9));
                transform.position = new Vector2(foodPos.x, foodPos.y);
            }

            public void SnakeAte()
            {
                if (Vector3.Distance(foodPos, snakeMove) < DISTANCE_THRESHOLD)
                {
                    SpawnApple();
                }
            }
        }

Now remember that since your teleporting the apple to a purely random location it might teleport right back on top of your snake:).现在请记住,由于您将苹果传送到一个纯粹随机的位置,它可能会立即传送回您的蛇的顶部:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM