首页 > 解决方案 > 当我使用这个脚本时,它会导致我的游戏崩溃。我究竟做错了什么?

问题描述

我想在事件触发后关灯几秒钟,但它不起作用。我对 C# 还是很陌生,所以如果代码很难看,我很抱歉 :(

[SerializeField] static public bool lightsOut;
private Light lightComponent;

void Start()
{
    lightComponent = gameObject.GetComponent<Light>();
    Time.timeScale = 0;
}

void Update()
{
    if (DeleteAfterFix.isFixed1)
    {
        TurnOffLights();
    }
}

IEnumerator WaitAndTurnOn()
{
    yield return new WaitForSeconds(2);
    TurnLightsOn();
}

void TurnOffLights()
{
    Destroy(lightComponent);
    WaitAndTurnOn();
}

void TurnLightsOn()
{
    gameObject.AddComponent<Light>(); 
    gameObject.GetComponent<Light>().type = 0;
    gameObject.GetComponent<Light>().intensity = 1 / 3;
    gameObject.GetComponent<Light>().range = 15 / 2;
    gameObject.GetComponent<Light>().spotAngle = 165;
}

标签: unity3d

解决方案


呼吁

Time.timeScale = 0;

inStart()函数停止游戏时间,即暂停游戏。删除它。

WaitAndTurnOn应该作为协程调用:

StartCoroutine(WaitAndTurnOn());

Update如果您使用协程,则不需要该功能。

void Start()
{
    StartCoroutine(WaitAndTurnOn());
}

IEnumerator WaitAndTurnOn()
{
    yield return new WaitForSeconds(2);
    TurnLightsOn();
}

void TurnLightsOff()
{
    Destroy(GetComponent<Light>());
    StartCoroutine(WaitAndTurnOn());
}

void TurnLightsOn()
{
    gameObject.AddComponent<Light>(); 
    gameObject.GetComponent<Light>().type = 0;
    gameObject.GetComponent<Light>().intensity = 1 / 3;
    gameObject.GetComponent<Light>().range = 15 / 2;
    gameObject.GetComponent<Light>().spotAngle = 165;
}

推荐阅读