I have the following problem:
I am trying to load data from a playfab server and store it on a script in 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
}
Everything works, except of the last line, which is adding the newly created script to the corresponding list on the script performing this action.
Is it not possible for unity to just store scripts somewhere without them being attached to gameobjects?
CodePudding user response:
Yes, it is possible to do so without attaching to a GameObject but for that to work your BuildingScript need to stop inheriting from MonoBehaviour.
Current BuildingScript:
public class BuildingScript : MonoBehaviour {}
New BuildingScript:
public class BuildingScript {}
NOTES :
You will not be able to use certain classes and methods inside your BuildingScript class if you stop inheriting from MonoBehaviour. You will also not be able to add your BuildingScript to a GameObject anymore.
When creating a class inheriting from MonoBehaviour do not create an object like this:
BuildingScript _placeholder = new BuildingScript();
Instead it is meant to be added to a GameObject like this:
yourGameObject.AddComponent<BuildingScript>();