Item class won't allow GameObject variable

My Item Class script can be fed values from a deserialized XML file, but I also want it to have a gameobject variable that holds the item’s instantiated gameobject if it is equipeed by a character.

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Serialization;
     
     
    [System.Serializable]
    public class Item {
         [XmlAttribute("name")]
          public string name = "";
          [XmlAttribute("value")]
          public int value = 0;

          public GameObject worldItem;//this is the "bad line" :)
    }

During runtime, I get the error

InvalidOperationException: To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. UnityEngine.Transform does not implement Add(System.Object).

As the error states you can not serialize the Transform component of the game object directly.

But one workaround is to use ISerializationSurrogate. Using this you can serialize the Transform component of game object and add it to your Item class.

Check out the example code at SurrogateSelector Class (System.Runtime.Serialization)

I just found the answer :slight_smile: Since I didn’t want to serialize the Item class anyway, I just needed to add “[XmlIgnore]” before the gameobject variable declaration.