大家好。我决定在 Unity 中制作 2d 游戏,但我遇到了问题。游戏的本质是你需要控制角色并收集硬币,硬币应该每两秒出现在随机位置,当角色接触它们时应该消失。但问题是,当角色接触硬币时,OnTriggerEnter2D 事件不会触发,延迟函数“Thread.Sleep();”也不起作用。当我将它添加到代码并开始游戏时,Unity 冻结并且不响应任何点击。如何使用 OnTriggerEnter2D 和 Thread.Sleep() 解决这两个问题;
代码如下:
GameController.cs(其中包含每两秒生成硬币的代码):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.Threading.Tasks;
public class GameController : MonoBehaviour
{
public GameObject coin;
public static GameObject inst_obj;
private void SpawnCoin()
{
int randY = Random.Range(5, -6);
int randX = Random.Range(-3, 3);
Vector3 spawnPosition = new Vector3(randX, randY);
Quaternion spawnRotation = Quaternion.identity;
inst_obj = Instantiate(coin, spawnPosition, spawnRotation) as GameObject;
}
private void FixedUpdate()
{
Thread.Sleep(2000);
SpawnCoin();
}
}
这是 Player.cs 脚本(包含相同的 OnTriggerEnter2D):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Threading;
using System;
using System.Threading.Tasks;
public class Player : MonoBehaviour
{
public FixedJoystick joystick;
public float velocity = 1.0f;
public float velocityRightLeft = 1.0f;
private int coins1 = 0;
//GameController gameController = new GameController();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
gameObject.GetComponent<Rigidbody2D>().transform.position += new Vector3(joystick.Direction.x * velocityRightLeft * Time.fixedDeltaTime, joystick.Direction.y * velocity * Time.fixedDeltaTime, 0);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag.Equals("Coin"))
{
Destroy(GameController.inst_obj);
}
}
}
至少 - 首先,您在 Update 中使用 Thread.Sleep... 它会在每帧冻结应用程序 2 秒。其次, Thread.Sleep 根本不应该在 Unity 中使用。阅读协程。
https://docs.unity3d.com/Manual/Coroutines.html
https://forum.unity.com/threads/can-i-use-thread-sleep-milliseconds-instead-of-a-coroutine-to-pause-a-script.971031/
或者,如果您非常简单地需要它,那么上面链接中的示例...