[英]Is there a way to outline a GameObject through a C# script in 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.