只创建并保存脚本的实例



我有以下问题:

我正在尝试从playfab服务器加载数据,并将其存储在Unity中的脚本中。

if (_item.ItemClass == "building")
{
string _id = _item.ItemId;
Debug.Log("loaded building: id: " + _id);
int _idInt = int.Parse(_id);

BuildingScript _placeholder = new BuildingScript();                             // create the building, that will be added to the players local inventory
// then translate its custom data:

// _item.CustomData

_placeholder.SO_of_This = GameManager.instance.buildingArray[_idInt];           // add the loaded buildingsList Scriptable Object to the placeholder, to later load the correct model
Debug.Log("SO_Building of the building we found: " + _placeholder.SO_of_This.name);

buildingsList.Add(_placeholder);                                                    // add the placeholder to the player
}

除了最后一行,一切都正常,这一行将新创建的脚本添加到执行此操作的脚本的相应列表中。

unity不可能只将脚本存储在某个地方而不将其附加到游戏对象上吗?

是的,可以在不附加到GameObject的情况下执行此操作,但要使BuildingScript工作,需要停止从MonoBehavior继承。

当前构建脚本:

public class BuildingScript : MonoBehaviour {}

新建脚本:

public class BuildingScript {}

注意:

  • 如果停止从MonoBehavior继承,您将无法在BuildingScript类中使用某些类和方法。您也将无法再将BuildingScript添加到GameObject中。

  • 创建继承自MonoBehavior的类时,不要创建这样的对象:

    BuildingScript _placeholder = new BuildingScript();
    
  • 相反,它被添加到游戏对象中,如下所示:

    yourGameObject.AddComponent<BuildingScript>();
    

最新更新