Unity Static member `UpgradeManager.tickValue' cannot be accessed with an instance reference, qualify it with a type name instead

ぃ、小莉子 提交于 2019-12-13 10:16:50

问题


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:


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;
}


来源:https://stackoverflow.com/questions/39999971/unity-static-member-upgrademanager-tickvalue-cannot-be-accessed-with-an-instan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!