简体   繁体   English

如何从 Unity3d 和 C# 中的另一个脚本访问在单例类中创建的列表

[英]How to access lists created in a singleton class from another script in Unity3d and C#

I am working on an RPG in Unity3d.我正在 Unity3d 中开发 RPG。 I have successfully refactored the code to run an SQL database and into a singleton pattern.我已经成功地将代码重构为运行 SQL 数据库并转换为单例模式。 The gameobject is created at runtime.游戏gameobject是在运行时创建的。

In each table I create a list based on its property script;在每个表中,我根据其属性脚本创建一个列表; I'm creating it there because it accesses the database.我在那里创建它是因为它访问数据库。 The other script is attached to the top panel where I want to display the character's name and stats, but I'm having trouble getting access to the list.另一个脚本附加到顶部面板,我想在其中显示角色的姓名和统计信息,但我无法访问列表。

PlayerDatabaseManager PDM; 

void Awake()
{
    PlayerDatabaseManager.Instance.LoadPersonal();
}

// Use this for initialization
void Start () 
{
    PDM.GetComponent<PlayerDatabaseManager>.Personal();
    Personal = PDM.Personal.Name();
}

I'm confused what to put where.我很困惑该放什么。 Does personal need to be of type databasemanager or of type personal ?个人需要是databasemanager类型还是personal类型?

I think your structure is a bit confused.我觉得你的结构有点混乱。 If PlayerDatabaseManager is a singleton, you shouldn't be calling LoadPersonal from a different component - it should be dealing with that itself when it needs to, to be well encapsulated.如果PlayerDatabaseManager是一个单例, LoadPersonal应从不同的组件调用LoadPersonal - 它应该在需要时自行处理,以进行良好封装。

Additionally, if PDM is already of type type PlayerDatabaseManager , there is no need to called GetComponent<PlayerDatabaseManager on it.此外,如果PDM已经是PlayerDatabaseManager类型,则无需在其上调用GetComponent<PlayerDatabaseManager

I think what you want is:我想你想要的是:

1) In PlayerDatabaseManager Awake() : 1) 在PlayerDatabaseManager Awake()

Instance = this;

2) In other classes that access information, for example the name in Personal 2)在其他访问信息的类中,例如Personal的姓名

void Start() {
    Name = PlayerDatabaseManager.Instance.Personal.Name()
}

3) Set the execution order for PlayerDatabaseManager so that it runs before other scripts, or make sure it is loaded in the first scene before any other gameobjects with scripts that will access it. 3) 设置 PlayerDatabaseManager 的执行顺序,使其在其他脚本之前运行,或者确保它在第一个场景中加载到任何其他具有访问它的脚本的游戏对象之前。

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

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