【问题标题】:How do I change a variable alternately in that C# code? [closed]如何在该 C# 代码中交替更改变量? [关闭]
【发布时间】:2020-04-22 16:25:47
【问题描述】:
  void Update(){

      public int x = -10;

      if (Input.GetKey("w")){


        GetComponent<Rigidbody2D>().velocity = new Vector3(10, x);

      }
   }

当我按下 w 键时,变量 x 为 -10,当我再次按下 w 时,变量 x 应更改为 9。当我再次按下“w”时,x 应再次为 -10。如何在我的代码中做到这一点?

【问题讨论】:

  • 不要标记不相关的语言。还显示您尝试了什么以及问题出在哪里
  • 您可以使用XOR0 ^ 1 == 1 然后1 ^ 1 == 0。这个^ 1 基本上会来回切换

标签: c# unity3d


【解决方案1】:

这是您的代码,只需在 Update 函数中使用 GetKeyDown。如果您喜欢更紧凑的代码,也可以使用布尔或模运算符。下次,请记得在要求之前发布您的解决方案。

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

public class PingPong: MonoBehaviour 
{
   private int counter = 0;

   void Update()
   {
      if (Input.GetKeyDown(KeyCode.W))
      {
         if (counter == 0)
            counter = 1;
         else
            counter = 0;

         Debug.Log(counter);
      }
   }
}

【讨论】:

  • 但在您的代码中,1 和 0 只打印了两次。我想要一个循环,交替打印 1 和 0。
  • 函数Update每帧都会被调用,更多信息请查看文档。这是完美的工作。
  • 好的,但我如何在顶部的代码中执行此操作。
猜你喜欢
  • 2016-09-29
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多