首页 > 解决方案 > Unity中GameObject的引用脚本类

问题描述

我有一个建筑物类,我想将它连接到建筑物的游戏对象。在课堂上,我有属性:名称、级别、信息。我拥有建筑物的资产(例如农场、城堡、港口)。我有一个游戏类,我在其中创建对象。游戏类用于存储对象,因此可以在整个游戏中调用它们,从而可以像这样保存游戏。

我真的无法通过谷歌搜索找到我想要的东西,我也很难描述我的意思。

建筑类:

[System.Serializable]
public class BuildingObject
{
    public string name;
    public int level;
    public string information;

    public BuildingObject(string information)
    {
        this.name = "";
        this.level = 0;
        this.information = information;
    }
}

这是我创建对象的 Game 类。我希望在游戏对象中引用创建的对象,因此我可以通过在其他文件中使用某些游戏对象的属性并保持某些游戏对象的关卡进度来调用某些游戏对象的属性。

public static Game current;

public BuildingObject church;
public BuildingObject castle;
public BuildingObject fort;
public BuildingObject farm;
public BuildingObject pub;
public BuildingObject houses;

public PlayerObject player;

public StoryObject story;

public Game()
{
    church = new BuildingObject("Informatie over de kerk");
    castle = new BuildingObject("Informatie over het kasteel");
    fort = new BuildingObject("Informatie over het fort");
    farm = new BuildingObject("Informatie over de boerderij");
    pub = new BuildingObject("Informatie over de kroeg");
    houses = new BuildingObject("Informatie over de huizen");

    player = new PlayerObject();

    story = new StoryObject();
}

我想根据 GameObjects 连接/引用 Game 对象中创建的对象。如果我在层次结构中创建了城堡游戏对象,我想要游戏对象中城堡对象的属性。如果有另一种更好或更简单的方法,请告诉我,我是统一的新手。

标签: c#unity3dgameobject

解决方案


使用预制件

gameObjects您可以在层次结构中存储要创建的模板。您需要将脚本附加为Component,可以通过调用来引用 GameObject.GetComponent<BuildingObject>()


推荐阅读