use 2019.1.8f1 ver
I've been referring to a lot of information, but an unknown error bothers me.
Error
SerializationException: Type 'UnityEngine.GameObject' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
[System.Serializable]
public class Map
{
public Node[,] nodes;
}
[System.Serializable]
public class Node
{
public GameObject tile;
public bool walkable;
public Vector3 worldPosition;
public int gridX;
public int gridY;
public int gCost;
public int hCost;
public int FCost { get { return gCost + hCost; } }
public Node(bool _walkable, Vector3 _worldPosition, int _gridX, int _gridY)
{
walkable = _walkable;
worldPosition = _worldPosition;
gridX = _gridX;
gridY = _gridY;
}
}
[System.Serializable]
public class Grid : MonoBehaviour
{
public Node[,] grid;
public void SaveMapData()
{
Debug.Log("Save");
FileStream stream = File.Create(Application.persistentDataPath + path);
BinaryFormatter bf = new BinaryFormatter();
Map map = new Map();
map.nodes = grid.grid;
bf.Serialize(stream, map);
stream.Close();
}
Your Node class references the GameObject class here:
public GameObject tile;
The best solution would be to get rid of that reference. This would also improve the decoupling of your model from the view.
Or try the [NonSerialized] attribute as a quick fix:
[NonSerialized] public GameObject tile;
Related
Need your help.
Easily create a foldout element with toggle list. Like that
But I need to create foldout element with toggle in a header. Like that
I think it's possible because scripts header already have this
I tried to find the answer here but didn't find anything like it.
Thank you for help
You can override how your Serializable class is rendered using EditorGUI by creating a custom PropertyAttribute and PropertyDrawer.
Example
I cooked up an attribute that takes a boolean field (specified by you) and instead of rendering it as usual, it renders it as a checkbox at the top. You can have any number of boolean fields inside your class, they should render just fine.
This implementation renders only boolean fields. If you wish to render other kind of stuff besides that, feel free to extend this solution.
Implementation
using UnityEngine;
public class ToggleListAttribute : PropertyAttribute
{
public string StatusPropertyName { get; private set; }
public ToggleListAttribute(string statusPropertyName)
{
StatusPropertyName = statusPropertyName;
}
}
using System;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(ToggleListAttribute))]
public class ToggleListDrawer : PropertyDrawer
{
private bool show;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var statusProperty = GetStatusPropertyFrom(property);
var foldoutRect = GetLinePositionFrom(position, 1);
show = EditorGUI.Foldout(
foldoutRect,
show,
string.Empty,
false);
statusProperty.boolValue = EditorGUI.ToggleLeft(
foldoutRect,
property.displayName,
statusProperty.boolValue);
if (show)
RenderSubproperties(property, position);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
if (show)
return EditorGUIUtility.singleLineHeight * (GetBooleanPropertyCount(property) + 1);
else
return EditorGUIUtility.singleLineHeight;
}
private SerializedProperty GetStatusPropertyFrom(SerializedProperty property)
{
var listAttribute = attribute as ToggleListAttribute;
var statusProperty = property.FindPropertyRelative(
listAttribute.StatusPropertyName);
if (statusProperty == null)
throw new Exception($"No property named \"{listAttribute.StatusPropertyName}\" found!");
return statusProperty;
}
private void RenderSubproperties(SerializedProperty property, Rect position)
{
var innerPosition = new Rect(
position.x + EditorGUIUtility.standardVerticalSpacing * 4,
position.y,
position.width,
position.height);
var statusProperty = GetStatusPropertyFrom(property);
int line = 2;
foreach (var instance in property)
{
var subproperty = instance as SerializedProperty;
if (subproperty.propertyType != SerializedPropertyType.Boolean ||
subproperty.name == statusProperty.name)
{
continue;
}
subproperty.boolValue = EditorGUI.ToggleLeft(
GetLinePositionFrom(innerPosition, line),
subproperty.displayName,
subproperty.boolValue);
line++;
}
}
private int GetBooleanPropertyCount(SerializedProperty property)
{
int count = 0;
foreach (var instance in property)
{
var subproperty = instance as SerializedProperty;
if (subproperty.propertyType != SerializedPropertyType.Boolean)
continue;
count++;
}
return count - 1;
}
private Rect GetLinePositionFrom(Rect rect, int line)
{
float heightModifier = EditorGUIUtility.singleLineHeight * (line - 1);
return new Rect(
rect.x,
rect.y + heightModifier,
rect.width,
EditorGUIUtility.singleLineHeight);
}
}
Usage
using System;
using UnityEngine;
public class Example : MonoBehaviour
{
[ToggleList("enabled")]
public RenderList list1;
[ToggleList("enabled")]
public RenderList2 list2;
}
[Serializable]
public class RenderList
{
public bool enabled;
public bool floor;
public bool car;
public bool train;
}
[Serializable]
public class RenderList2
{
public bool enabled;
public bool one;
public bool two;
public bool three;
public bool four;
public bool five;
public bool six;
public bool seven;
}
Use EditorGUILayout.InspectorTitlebar(foldout: foldout, editor: targetEditor);
I am following this talk https://www.youtube.com/watch?v=BNMrevfB6Q0 and try to understand how to spawn units as I click my mouse (for testing purposes).
For this in general, I created a UnitBase etc. which implements IConvertGameObjectToEntity::Convert to make sure all units can be converted to a Entity objects and looks like this:
namespace Units
{
public abstract class UnitBase : MonoBehaviour, IConvertGameObjectToEntity
{
public float health;
public bool selected;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new Translation {Value = transform.position});
dstManager.AddComponentData(entity, new Rotation {Value = transform.rotation});
dstManager.AddComponentData(entity, new Selected {Value = selected});
dstManager.AddComponentData(entity, new Health {Value = health});
}
}
public abstract class MobileUnitBase : UnitBase
{
public float speed;
public new void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
base.Convert(entity, dstManager, conversionSystem);
dstManager.AddComponentData(entity, new Speed {Value = speed});
}
}
}
These are the main components:
namespace ECS.Components
{
public class Health : IComponentData
{
public float Value;
}
public class Speed : IComponentData
{
public float Value;
}
public class Selected : IComponentData
{
public bool Value;
}
}
Now, in my Test script I have this:
public class Test : MonoBehaviour
{
public GameObject unitPrefab;
private EntityManager _entityManager;
private Entity _unitEntityPrefab;
// Start is called before the first frame update
void Start()
{
_entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
_unitEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(unitPrefab, World.Active);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
SpawnUnit(15, 15);
}
}
private void SpawnUnit(float x, float z)
{
Debug.Log($"Spawning unit at x:{x} y:{z}");
var unitEntity = this._entityManager.Instantiate(this._unitEntityPrefab);
_entityManager.SetComponentData(unitEntity, new Translation {Value = new Vector3(x, 1, z)});
_entityManager.SetComponentData(unitEntity, new Rotation {Value = Quaternion.Euler(0, 0, 0)});
_entityManager.SetComponentData(unitEntity, new Health {Value = 100f});
_entityManager.SetComponentData(unitEntity, new Selected {Value = false});
}
}
Where unitPrefab is just a simple GameObject that has a Capsule on it and a, basically empty, script which is empty for now:
public class UnitScript : UnitBase
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
The thing is, as I click, the entities get created but the unit is not rendered.
Obviously I am missing something but I don't see what it is.
Any help would be much appreciated!
Like title,I didn't create a custom inspector for ScriptableObject,and I googled, most of the answers are using SetDirty(object) but it did't work.When I modify any of the code in the project and Unity will refactor the C# code, some of the ScriptableObjects will be displayed in the Inspector panel,not all SOs are displayed but partially displayed,I checked these displayed SOs,data is not lost;When I reopen the project again,and then click SO in Project panel,Inspector panel has nothing;
as you can see, MouseModuleData is not display which is created from last time i opened Unity,MouseModuleData1 is created from this time;So I think if there is a problem with my data structure.
/// <summary>
/// Base Class of Module Data
/// </summary>
public abstract class PitchModuleBaseData : ScriptableObject, IEnumerable
{
public abstract IEnumerator GetEnumerator();
}
/// <summary>
/// Face Module Data
/// </summary>
[System.Serializable, CreateAssetMenu(fileName = "MouseModuleData", menuName = "AvatarData/MouseModuleData")]
public class MouthModuleData : PitchModuleBaseData
{
public BoneData MouthCornerLeft;
public BoneData MouthCornerRight;
public BoneData LeapUp;
public BoneData LeapMiddle;
public BoneData LeapDown;
public BoneData MouseRoot;
public MouthModuleData()
{
MouthCornerLeft = new BoneData(PitchFaceConst.Mouth_CornerL, PitchFaceConst.Mouth_CornerR);
MouthCornerRight = new BoneData(PitchFaceConst.Mouth_CornerR, PitchFaceConst.Mouth_CornerL);
LeapDown = new BoneData(PitchFaceConst.Mouth_LeapDown);
LeapMiddle = new BoneData(PitchFaceConst.Mouth_LeapMiddle);
LeapUp = new BoneData(PitchFaceConst.Mouth_LeapUp);
MouseRoot = new BoneData(PitchFaceConst.Mouth_Root);
}
public override IEnumerator GetEnumerator()
{
BoneData[] arr = new BoneData[6];
arr[0] = MouthCornerLeft;
arr[1] = MouthCornerRight;
arr[2] = LeapUp;
arr[3] = LeapDown;
arr[4] = MouseRoot;
arr[5] = LeapMiddle;
return new DataEnumerator(arr);
}
}
So I did a test; I created a data like the one above.
public abstract class ABData : ScriptableObject, IEnumerable
{
public abstract IEnumerator GetEnumerator();
}
[System.Serializable, CreateAssetMenu(fileName = "TestData", menuName = "Create/TestData")]
public class TestData : ABData
{
public TestData()
{
data = new BoneData();
Middle = new BoneData(PitchFaceConst.Eye_Mid);
Left = new BoneData(PitchFaceConst.Eye_Left, PitchFaceConst.Eye_Right);
Right = new BoneData(PitchFaceConst.Eye_Right, PitchFaceConst.Eye_Left);
EyeLeft1 = new BoneData(PitchFaceConst.Eye_L1, PitchFaceConst.Eye_R1);
EyeLeft2 = new BoneData(PitchFaceConst.Eye_L2, PitchFaceConst.Eye_R2);
EyeLeft3 = new BoneData(PitchFaceConst.Eye_L3, PitchFaceConst.Eye_R3);
EyeLeft4 = new BoneData(PitchFaceConst.Eye_L4, PitchFaceConst.Eye_R4);
EyeRight1 = new BoneData(PitchFaceConst.Eye_R1, PitchFaceConst.Eye_L1);
EyeRight2 = new BoneData(PitchFaceConst.Eye_R2, PitchFaceConst.Eye_L2);
EyeRight3 = new BoneData(PitchFaceConst.Eye_R3, PitchFaceConst.Eye_L3);
EyeRight4 = new BoneData(PitchFaceConst.Eye_R4, PitchFaceConst.Eye_L4);
}
public BoneData data;
public BoneData Middle;
public BoneData Left;
public BoneData Right;
public BoneData EyeLeft1;
public BoneData EyeLeft2;
public BoneData EyeLeft3;
public BoneData EyeLeft4;
public BoneData EyeRight1;
public BoneData EyeRight2;
public BoneData EyeRight3;
public BoneData EyeRight4;
public override IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}
Then let me go crazy, something happened.TheTestData is Showed as normal Whether it is reopened or not, it works just like a normal OS.
Please help me, let me get on the right track.
SOLVED:
I put all ScriptableObject code in one .cs file, After reload the project,Unity can't find the ScriptableObject script instanceID,you can let Inspector to DEBUG mode to check!
The answer is every ScriptableObject you should have a reference .cs file with it along;
I'm using Zenject framework and I want instansiate gameObject for class created by factory. For this I'm using something like this in GameInstaller
Container.BindFactory<int,int,Hex, Hex.Factory().
FromComponentInNewPrefab(_settings.PlainHexPrefab[0]).
WithGameObjectName("Hex").
UnderTransformGroup("Zenject");`
It's work fine, but in my case in _settings.PlainHexPrefab I have collection GameObjects and I need choose one of them dependency by properties from Hex object. How could I do it?
Here's three ways that might work for you:
FromMethod
public class Hex : MonoBehaviour
{
public class Factory : PlaceholderFactory<int, int, Hex>
{
}
}
public class TestInstaller : MonoInstaller<TestInstaller>
{
public GameObject[] HexPrefabs;
public override void InstallBindings()
{
Container.BindFactory<int, int, Hex, Hex.Factory>().FromMethod(CreateHex);
}
Hex CreateHex(DiContainer _, int p1, int p2)
{
var prefab = HexPrefabs[Random.RandomRange(0, HexPrefabs.Count() -1)];
return Container.InstantiatePrefabForComponent<Hex>(prefab);
}
}
Custom Factory
public class HexFactory : IFactory<int, int, Hex>
{
readonly DiContainer _container;
readonly GameObject[] _prefabs;
public HexFactory(
GameObject[] prefabs,
DiContainer container)
{
_container = container;
_prefabs = prefabs;
}
public Hex Create(int p1, int p2)
{
var prefab = _prefabs[Random.RandomRange(0, _prefabs.Count() -1)];
return _container.InstantiatePrefabForComponent<Hex>(prefab);
}
}
public class TestInstaller : MonoInstaller<TestInstaller>
{
public GameObject[] HexPrefabs;
public override void InstallBindings()
{
Container.BindFactory<int, int, Hex, Hex.Factory>()
.FromIFactory(b => b.To<HexFactory>().AsSingle().WithArguments(HexPrefabs));
}
}
Sub factories in custom factory. This also has the advantage that each prefab factory should be 'validated'
public class CustomHexFactory : IFactory<int, Hex>
{
readonly List<Hex.Factory> _subFactories;
public CustomHexFactory(List<Hex.Factory> subFactories)
{
_subFactories = subFactories;
}
public Hex Create(int p1)
{
return _subFactories[Random.RandomRange(0, _subFactories.Count() -1)].Create(p1);
}
}
public class TestInstaller : MonoInstaller<TestInstaller>
{
public GameObject[] HexPrefabs;
public override void InstallBindings()
{
foreach (var prefab in HexPrefabs)
{
Container.BindFactory<int, Hex, Hex.Factory>().FromComponentInNewPrefab(prefab)
.WhenInjectedInto<CustomHexFactory>();
}
Container.BindFactory<int, Hex, Hex.Factory>().FromFactory<CustomHexFactory>();
}
}
Ok so I followed the Unity3D data persistence tutorial, everything is going smoothly until I tried to save a Vector3 type of data. The tutorial only shows how to save int and strings.
When I used the function Save() , the consoles shows me that says: "SerializationException: Type UnityEngine.Vector3 is not marked as Serializable.
But as you can see from my code, I included it under the Serializable part. I am trying to save my playerPosition. Thanks
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Generic;
public class GameManager : MonoBehaviour
{
public static GameManager control;
public float health;
public float mana;
public float experience;
public Vector3 playerPosition;
public List<Item> inventory = new List<Item>();
void Awake()
{
if(control == null)
{
DontDestroyOnLoad(gameObject);
control = this;
}
else if(control != this)
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start (){}
// Update is called once per frame
void Update () {}
void OnGUI()
{
GUI.Box(new Rect(10, 10, 100, 30), "Health: " + health);
GUI.Box(new Rect(10, 30, 100, 30), "Mana: " + mana);
GUI.Box(new Rect(10, 50, 100, 30), "Experience: " + experience);
}
public void SaveSlot1()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath +
"/saveData1.dat");
PlayerData data = new PlayerData();
data.health = health;
data.mana = mana;
data.experience = experience;
data.playerPosition = playerPosition;
for(int i = 0; i <inventory.Count; i++)
{
//data.inventory[i] = inventory[i];
}
bf.Serialize(file, data);
file.Close();
}
public void LoadSlot1()
{
if(File.Exists(Application.persistentDataPath +
"/saveData1.dat") )
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath +
"/saveData1.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
health = data.health;
mana = data.mana;
experience = data.experience;
playerPosition = data.playerPosition;
for(int i = 0; i <inventory.Count; i++)
{
//inventory[i] = data.inventory[i];
}
}
}
[Serializable]
class PlayerData
{
public float health;
public float mana;
public float experience;
public Vector3 playerPosition;
public List<Item> inventory = new List<Item>();
//position
//spells
//
}
}
Marking something as Serializable just let's .NET to know that you are going to be using serialization. At that point every property all the way down the data model must also be serializable, either by being inherently serializable like ints and strings, or being a type that is also marked as serializable. There's a couple of options
[Serializable]
class PlayerData
{
public PlayerData()
{
playerPosition = Vector3.zero;
}
public float health;
public float mana;
public float experience;
[NonSerialized]
public Vector3 playerPosition;
public double playerPositionX
{
get
{
return playerPosition.x;
}
set
{
playerPosition.x = value;
}
}
public double playerPositionY
{
get
{
return playerPosition.y;
}
set
{
playerPosition.y = value;
}
}
public double playerPositionZ
{
get
{
return playerPosition.z;
}
set
{
playerPosition.z = value;
}
}
public List<Item> inventory = new List<Item>();
}
This first option will not serialize the vector field, and instead use the properties. Having a vector to start with is important.
The other option is to implement the ISerializable interface on your class and then specifically control what fields are being written. The interface is somewhat tricky to implement, here is a MSDN link that explains some good and bad examples