Anyway to save a GameObject Reference in XML?

Anyone have any ideas or workaround for this?

My enemies have a “Target”, the target is assigned during runtime. For example, if they see the player the player may become their “Target”. If an enemy shoots another enemy then that enemy may become their “Target”.

Is there anyway to save this reference to XML? Or will I need to do some kind of workaround like save the targets vector3, then on load find the enemy/player closest to that vector3 and fill in the reference.

I already have positions/rotations/enemy states/ammo and what not saved to XML, just not sure how to account for this “Target” variable.

Thanks!

Assign a unique identifier to each object with the potential to be a target. You then save that identifier, not the reference itself.

When you go to reconnect this reference, you loop through all potential targets for the one with the correct unique identifier, and set the reference to that one.

My personal preference is to use a ulong for the identifier. When you create new objects, you do something along these lines:

private ulong myIdentifier;
private static ulong lastUniqueIdentifier;

void Awake()
{
    assignIdentifier();
}

void assignIdentifier()
{
    lastUniqueIdentifier++;
    myIdentifier = lastUniqueIdentifier;
}

You’d also add code for creating the object based on your save game data instead of creating a new one, and setting lastUniqueIdentifer to the highest identifier found in your save game file. I’m assuming this is for some kind of save game system.

1 Like

Yeah I thought of that too but it seems really annoying to give every enemy their own ID no? I guess it wouldn’t be so bad…

1 Like

In the extremely unlikely chance you’re using DOTS they should already have an ID number.

Assign an unique ID to them during serialization. Load the unique ID during deserialization, and then find targets via that unique ID.

3 Likes

I ended up doing this. I was worried the wrong Id’s would get assigned to the wrong enemies especially if enemies were added to the hierarchy by spawning in later. But it doesn’t seem to be an issue actually, works good, thanks for the help all.