【发布时间】:2020-01-04 05:14:13
【问题描述】:
我在网站上多次看到这个问题,但大多数解决方案似乎表明我应该将其设为实例变量而不是静态变量。然而,Singleton 模式的全部意义在于始终引用的这个静态对象。以下是我看过的链接:
Member cannot be accessed with an instance reference; qualify it with a type name
Member '<method>' cannot be accessed with an instance reference
最后一个链接将我引向以下内容:
What does the 'static' keyword do in a class?
我觉得我确实理解这一点。 Singleton 的重点是所有类都共享这个实例,所以感觉很完美?我没看到问题?根据 Singleton 约定和坦率的逻辑,它应该是 static。
我很团结,正在尝试为一些同学和我正在尝试制作的游戏制作库存系统。我已经设置了 InventoryUI,但是我想构建一个在游戏中始终存在的静态库存。 InventoryUI 将从这个 Singleton 类中提取必要的数据。
换句话说,PlayerInventory 将充当 InventoryUI 的后端。 PlayerInventory 将是一个单例,InventoryUI 将从 PlayerInventory 中提取必要的数据
这是我的 Singleton 类的相关代码:
public class PlayerInventory : MonoBehaviour
{
private static PlayerInventory instance;
private PlayerInventory() { }
public static PlayerInventory getInstance()
{
if (instance == null)
return instance = new PlayerInventory();
return instance;
}
}
这是我的 InventoryUI 类的相关代码:
public class PlayerInventoryUI : MonoBehaviour
{
//Inventory Instance
static PlayerInventory inventory;
void Start()
{
inventory = inventory.getInstance();
//cannot be accessed with an instance reference Error occurs here.
}
}
如果可能,有人可以向我解释为什么会出现此错误以及可能的解决方案。
【问题讨论】: