我已經嘗試了幾種方法。我問了幾個朋友,但到目前為止似乎沒有任何效果。我已多次更改腳本,因此我不再嘗試其他方法。然而,這是給我的錯誤最少的一個。其他我不得不不斷地將其更改為 Unity 推薦的方式,但以死胡同告終,沒有任何效果。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightActivator : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
gameObject.SetActive(false);
}
else if (Input.GetKeyDown(KeyCode.Space))
{
gameObject.SetActive(true);
}
}
}
我希望能夠只用 1 個按鈕打開環境/定向燈。那不可能嗎?
uj5u.com熱心網友回復:
這里有兩個小缺陷
在你做完之后
gameObject.SetActive(false);這個完全相同的物件現在處于非活動狀態-> 該組件也是如此->
Update根本不再被呼叫;)你永遠只會處理第一種情況......第二個根本不會被呼叫,因為條件總是與第一個塊匹配!
而是將邏輯與目標物件分開并執行例如
// This class should go to a different object that is always active in your scene
public class LightActivator : MonoBehaviour
{
// Here you reference the object you want to (de)activate via drag&drop in the Inspector
public GameObject theLight;
void Update()
{
// You only need one condition check
if (Input.GetKeyDown(KeyCode.Space))
{
// INVERT the active state of the light object whatever it currently is
theLight.SetActive(!theLight.activeSelf);
}
}
}
為了將事物保持在一起,您可以例如簡單地使相應的光物件成為該物件的子LightActivator物件;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310983.html
下一篇:C#錯誤-Guid應包含32位數字和4個破折號(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
