簡體   English   中英

關閉和打開燈的腳本 [ C#,Unity 3d ]

[英]script to turn the light off and on [ C# , Unity 3d ]

我制作了這個小腳本,應該關閉和打開點燈的燈光......不幸的是,只有關閉按鈕起作用,之后它不會再次打開......也許腳本中有一些錯誤?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class TurnLight : MonoBehaviour {

public GameObject light;


private bool on = true ;


void OnTriggerStay(Collider other) {
       

    if (other.tag == "Player" && Input.GetKey(KeyCode.E) && !on)
    {
       
        light.SetActive(true);
        on = true;
    }
    else if (other.tag == "Player" && Input.GetKey(KeyCode.E) && on)
        {
        light.SetActive(false);
        on = false;
    }
  }
}

請檢查此鏈接以了解OnTriggerStay Function

觸發停留

另外請檢查那些以區分獲取密鑰獲取密鑰

問題是OnTriggerStay的調用不斷發生,並且您正在使用GetKey函數,如果玩家按下,它將始終返回 true。 因此,當您使用GetKey時,這將導致單按 E 將多次變紅。

這是我的解決方案

 public GameObject light; 

bool isPlayerStandingNear = false; 
private void Update()
{
    if(isPlayerStandingNear)
    {
        //Debug.Log("isPlayerStandingNear");
        if(Input.GetKeyDown(KeyCode.E))
        {
            Debug.Log("Light State : "+ light.active);

            light.SetActive(!light.active);
        }
    }
}

void OnTriggerStay(Collider other)
{
    
    if (other.tag == "Player")
    {
        isPlayerStandingNear = true;
    } 
}
private void OnTriggerExit(Collider other)
{
    if (other.tag == "Player")
    {
        isPlayerStandingNear = false;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM