简体   繁体   English

按下按钮时增加一个项目,Unity

[英]Incrementing an item when a button is pressed, Unity

I am trying to increment an item in Unity when a button is pressed.当按下按钮时,我试图在 Unity 中增加一个项目。 I set the item value like so item = shells;我像这样设置项目值item = shells; where shells are another variable that I set earlier in my code.其中 shell 是我之前在代码中设置的另一个变量。 I am doing it in this way so that I can change the item value to something else later on like item = fossils;我这样做是为了以后可以将项目值更改为其他值,例如item = fossils; . .

The problem is that unless I have it as shells++;问题是,除非我把它当作shells++; nothing will happen when I press the button.当我按下按钮时,什么都不会发生。

current code:当前代码:

public double shells; 

public addItem(){
item = shells; 
item++; 

this code does not do anything when the addItem method is called.调用 addItem 方法时,此代码不执行任何操作。

Code that works有效的代码

public double shells; 

public addItem(){
shells++; 

If there is a better way of doing this please let me know.如果有更好的方法,请告诉我。

The problem here is that you're dealing with "value types".这里的问题是您正在处理“值类型”。 The code you have in your first example is assigning item the value of shells .您在第一个示例中的代码是为item分配shells的值。 Once you do that, you have two variables - item and shells .一旦你这样做了,你就有两个变量—— itemshells When you increment the item value ( item++ ), you're ONLY incrementing the item variable.当您增加item值 ( item item++ ) 时,您只是在增加item变量。 So now item will have a value 1 greater than shells .所以现在item的值将大于shells 1。

What you COULD do if you chose, is this:如果您选择,您可以做的是:

public double shells; 

public addItem()
{
    item = shells; 
    item++;
    shells = item; // here, you're assigning shells the value of item.
}

The code itself is kind of pointless, but it demonstrates how you would get a modified value back into the original variable.代码本身有点毫无意义,但它演示了如何将修改后的值返回到原始变量中。

Here's Microsoft's page describing "value types". 这是Microsoft 描述“值类型”的页面。 It'll be beneficial for you to understand the difference between "value types" and "reference types" going forwards.了解“值类型”和“引用类型”之间的区别对您很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM