如何将游戏对象设置为非活动状态,然后在几秒钟后统一为活动状态



当玩家与游戏对象发生碰撞时,我想使游戏对象处于非活动状态(我已经做到了(。现在我想等待几秒钟,然后再次激活它。我该怎么做?

这是我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement: MonoBehaviour
{
private float chubbyScore = 0;
private float coin = 0;
public float speed = 1;
public float jump = 1;
void Update()
{
Vector3 playerMovement = Vector3.zero;
playerMovement.x = Input.GetAxis("Horizontal");
transform.position += playerMovement * speed * Time.deltaTime;
transform.Translate(Vector3.forward * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Rigidbody>().velocity = Vector3.up * jump;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
coin += 1;
chubbyScore += 50;
} 
}
}

创建一个简单的等待通用实用程序,如:

public class Waiter : MonoBehaviour
{
static Waiter instance = null;
static Waiter Instance
{
get
{
if (instance == null)
instance = new GameObject("Waiter").AddComponent<Waiter>();
return instance;
}
}
private void Awake()
{
instance = this;
}
private void OnDestroy()
{
if (instance == this)
instance = null;
}
IEnumerator WaitRoutine(float duration, System.Action callback)
{
yield return new WaitForSeconds(duration);
callback?.Invoke();
}
public static void Wait(float seconds, System.Action callback)
{
Instance.StartCoroutine(Instance.WaitRoutine(seconds, callback));
}
}

这会在需要时自动将自己注入游戏,您只需要创建脚本,现在在您的OnTriggerEnter

void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
collObj = other.gameObject;
collObj.SetActive(false);
Waiter.Wait(3, () =>
{
// Just to make sure by the time we're back to activate it, it still exists and wasn't destroyed.
if (collObj != null)
collObj.SetActive(true);
});
coin += 1;
chubbyScore += 50;
}
}

我会为偏移持续时间创建一个公共浮点,然后可以为计时器创建一个私有浮点。

设置对象活动状态的代码可能如下所示:

private float chubbyScore = 0;
private float coin = 0;
public float speed = 1;
public float jump = 1;
public float offsetTime = 2f;
private float timer = 0f;
private GameObject collObj;
void Update()
{
Vector3 playerMovement = Vector3.zero;
playerMovement.x = Input.GetAxis("Horizontal");
transform.position += playerMovement * speed * Time.deltaTime;
transform.Translate(Vector3.forward * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Rigidbody>().velocity = Vector3.up * jump;
}
if(!collObj.active)
{
timer += Time.deltaTime;
if(timer > offsetTime)
{
timer = 0f;
collObj.SetActive(true);
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
collObj = other.gameObject;
collObj.SetActive(false);
coin += 1;
chubbyScore += 50;
}
}

创建一个新函数,用于启用/禁用游戏对象。然后在start方法中重复调用最近生成的函数。

//Enables or Disables the GameObject every 5 seconds
void Start()
{
InvokeRepeating("Repeat", 0, 5);
}
void Repeat()
{
//Enable or Disable the GameObject
}

最新更新