Unity Static member `UpgradeManager.tickValue'

2019-09-20 14:57发布

How can i keep the structure like this, if the tickValue is static?

public float GetMoneyPerSec()
{
    float tick = 0;
    foreach (UpgradeManager item in items)
    {
        tick += item.tickValue;
    }
    return tick;
}

1条回答
再贱就再见
2楼-- · 2019-09-20 15:14

This error means your UpgradeManager looks as follows

public class UpgradeManager 
{
    public static float tickValue;
}

remove the static keyword and it will work in the context you have in your question.

If you want to use it in a static context you need to access it as follows, but then you can not use it in an instanced object (new UpgradeManager() creates an instance)

UpgradeManager.tickValue

so using it in your example.

public float GetMoneyPerSec()
{
    float tick = UpgradeManager.tickValue;
    // it cannot be used in a for-loop with each instance referencing it, static is a global, single value.
    return tick;
}

but what you may have wanted to do is this

public float GetMoneyPerSec()
{
    float tick = UpgradeManager.tickValue / items.length;
    // it cannot be used in a for-loop with each instance referencing it, static is a global, single value.
    return tick;
}
查看更多
登录 后发表回答