当前位置: 动力学知识库 > 问答 > 编程问答 >

c# 4.0 - Code Outputs mulitple times instead of just once (Unity C#)

问题描述:

Ok I am using Unity C# (MonoDevelop) and I am learning how to pull component variables from other components. Now I understand how to do that, but I am wondering why when I start the game and press the "F" key it prints "Hello I am a cube" and subtracts 1 from CubeTalkPoints at least 3-5 times. I want it to run the code once per key press.

void Update () {

if(Input.GetKey(KeyCode.F))

C_Talk(0);

}

void C_Talk(int SpellID = 0, int TalkPoint = 1)

{

CubeData CubeSub = GetComponent<CubeData>();

if (CubeSub.CubeTalkPoints >= TalkPoint)

{

CubeSub.CubeTalkPoints -= TalkPoint;

Debug.Log("Hello I am a Cube!");

}

}

网友答案:

Use GetKeyDown() instead of GetKey(). GetKeyDown() will only be true the first frame the button is down. GetKey() will be true every frame as long as the button is held down.

分享给朋友:
您可能感兴趣的文章:
随机阅读: