transform.SetParent(transform) not working for an instantiated game object

I’m working on a small prototype of a rewrite of an old game of mine, this time in Unity 5.2.0f3 Personal.

What I’m trying to do is make generic, data-driven units; when you click a spawn button, the game creates a cookie cutter unit, loads its stats, then instantiates a mesh, which has its parent set to the instance of the generic game object.

The code in question looks like this:

Driving Data - MapDetails.txt (JSON):

{
    "MapDetail":[
        {
            "Name":"Test Map",
            "Placements":[
                {
                    "Path":"Prefabs/GameObjects/Terrain (Grass)",
                    "Name":"Terrain",
                    "ObjectType":"GameObject",
                    "Placements":[
                        {
                            "Position":{
                                "x":0,
                                "y":0,
                                "z":0
                            },
                            "Rotation":{
                                "x":0,
                                "y":0,
                                "z":0
                            },
                            "Scale":{
                                "x":10,
                                "y":10,
                                "z":10
                            }
                        }
                    ]
                },
                {
                    "Path":"Prefabs/Units/Base Key Unit",
                    "Name":"Knight Castle",
                    "ObjectType":"Unit",
                    "Placements":[
                        {
                            "Position":{
                                "x":-7,
                                "y":0,
                                "z":0
                            },
                            "Rotation":{
                                "x":0,
                                "y":315,
                                "z":0
                            },
                            "Scale":{
                                "x":4,
                                "y":4,
                                "z":4
                            }
                        }
                    ]
                },
                {
                    "Path":"Prefabs/Units/Base Key Unit",
                    "Name":"Zombie Necropolis",
                    "ObjectType":"Unit",
                    "Placements":[
                        {
                            "Position":{
                                "x":7,
                                "y":0,
                                "z":0
                            },
                            "Rotation":{
                                "x":0,
                                "y":45,
                                "z":0
                            },
                            "Scale":{
                                "x":4,
                                "y":4,
                                "z":4
                            }
                        }
                    ]
                }
            ]
        }
    ]
}

Driving Data - Units.txt (JSON):

{
    "Units":[
        {
            "Name":"Knight Castle",
            "IsKeyUnit":true,
            "Faction":"Knights",
            "Stats":[
                {
                    "Name":"HP",
                    "Value":25,
                    "ValueCap":25,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"Attack",
                    "Value":1,
                    "ValueCap":4,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"Knockback",
                    "Value":15,
                    "ValueCap":4,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"MoveSpeed",
                    "Value":0,
                    "ValueCap":0,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"TurnSpeed",
                    "Value":0,
                    "ValueCap":0,
                    "FixedModifier":0,
                    "ScalingModifier":1
                }
            ],
            "AbilityNames":[
                "Recruit Footman"
            ]
            "MeshPath":"Visual/Meshes/kvz - castle"
        },
        {
            "Name":"Zombie Necropolis",
            "IsKeyUnit":true,
            "Faction":"Zombies",
            "Stats":[
                {
                    "Name":"HP",
                    "Value":25,
                    "ValueCap":25,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"Attack",
                    "Value":1,
                    "ValueCap":4,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"Knockback",
                    "Value":15,
                    "ValueCap":4,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"MoveSpeed",
                    "Value":0,
                    "ValueCap":0,
                    "FixedModifier":0,
                    "ScalingModifier":1
                },
                {
                    "Name":"TurnSpeed",
                    "Value":0,
                    "ValueCap":0,
                    "FixedModifier":0,
                    "ScalingModifier":1
                }
            ],
            "AbilityNames":[
                "Raise Ghoul"
            ]
            "MeshPath":"Visual/Meshes/kvz - grave"
        }
    ]
}

Specific code from UnitActuator.cs:

public void RealizeModel(UnitModel model)
    {
        Name = model.Name;
        IsKeyUnit = model.IsKeyUnit;
        Faction = model.Faction;
        Stats = model.Stats.DeepCopyList();

        Abilities = new List<Ability>();
        for (int i = 0; i < model.AbilityNames.Count; i++)
        {
            string currentName = model.AbilityNames[i];

            if (_abilityRepository == null)
                _abilityRepository = AbilityRepository.Instance;

            Ability actualAbility = _abilityRepository.GetAbilityByName(currentName);
            if (actualAbility == null)
            {
                DebugMessage("Could not map ability " + currentName + " because it doesn't exist in the Ability Repository.");
                continue;
            }

            Abilities.Add(actualAbility.DeepCopy());
        }

        Buffs = new List<Buff>();

        _deathObjectPath = model.DeathObjectPath;
        if(! string.IsNullOrEmpty(_deathObjectPath))
            DeathObject = (GameObject) Resources.Load(_deathObjectPath);

        // Problem is in this if block here...
        _meshPath = model.MeshPath;
        if (!string.IsNullOrEmpty(_meshPath))
        {
            // UnitMeshObject is a GameObject declared as a public variable for the behavior.
            GameObject unitMesh = Resources.Load<GameObject>(_meshPath);
            UnitMeshObject = (GameObject) Instantiate(unitMesh, Vector3.zero, Quaternion.identity);
            UnitMeshObject.name = "Mesh";
            UnitMeshObject.transform.SetParent(gameObject.transform);
        }
    }

What should be happening, is that when I load my scene, two opposing ‘Key Units’ - a Knight Castle, and a Zombie Necropolis - pre-spawn on opposite ends of the map. What’s happening is that, while the game objects, their selection reticules, and colliders are spawning in the right place with the right rotation, the two meshes are spawning in the middle of the map and not being parented to their respective game objects.

Question - Why is it that the following code:

GameObject unitMesh = Resources.Load<GameObject>(_meshPath);
UnitMeshObject =  (GameObject) Instantiate(unitMesh, Vector3.zero, Quaternion.identity);
UnitMeshObject.name = "Mesh";
UnitMeshObject.transform.SetParent(gameObject.transform);

Does not cause the mesh object to become a child of the Unit?

Hmm. I think it does cause the mesh object to become a child of the unit (if that’s what “gameObject” is). You can confirm this by looking in the Hierarchy view.

And the meshes are spawning in the middle of the map because that’s where you’ve told them to spawn (Vector3.zero for the second parameter to Instantiate).

The docs on SetParent are a little unclear, but the default (if you don’t pass ‘false’ for the optional second parameter) is to keep the world position/orientation of the child object even as it’s being parented to the new parent. So, it was at Vector3.zero before, and it’s still at Vector3.zero after.

So you can fix this in lots of ways:

  • pass ‘false’ as the second parameter to SetParent; OR,

  • pass gameObject.transform.position as the second parameter of Instantiate; OR,

  • assign the position you want after changing the parent

I often use that third approach, since then I don’t have to remember how SetParent works; there’s absolutely no ambiguity about it.

HTH,

  • Joe

@JoeStrout - Unfortunately, no, it’s not working at all.

“gameObject” is referring to the unit that is being ‘realized’ from the model; this code is supposed to instantiate the mesh as a game object, then make the unit the parent of the mesh game object.

Here’s a small screenshot of the hierarchy, to prove it. What should happen is, when the scene initializes, the GameObject ‘Knight Castle 1’ should have two child objects, ‘Mesh’ and ‘Reticule’. What’s actually happening is quite different - the Mesh object is not being added to ‘Knight Castle 1’ as a child.

2322806--156682--ZvK2 - Meshes Not Being Parented.png

I did attempt SetParent with false as the second parameter; it had no effect.

Hmm. I have never known SetParent to not actually set the parent. So, somewhere there is an invalid assumption here… and probably in code you’re not even thinking about at the moment. Some other bit that changes the parent afterwards, or maybe gameObject isn’t what you think it is when this code runs, or something like that.

When faced with something baffling like this, what I do is start stripping it down. Save a copy of your scene, and delete everything except the object(s) involved. Then delete all the scripts from those objects except the bare minimum needed. Then delete all the code from those scripts except the couple of lines that you believe should demonstrate the problem.

At some point in all that, the problem will go away, and you’ll say “What the —?” Then go look at whatever you last deleted, and find the clue.

The bug is in there, somewhere… you just need to napalm all its hiding places until you find it.

1 Like

@JoeStrout - You were right. There’s another file, MapLoader.cs, which is integral to the process, and calls the RealizeModel code above.

I had a simple logic sequence issue; I was trying to run the code on the in-memory high-level prototype of the game object, not the instance in the scene. I rearranged the logic such that the component would be found for the in-scene object, and RealizeModel called on that. That fixed it.

If you want to see what that code looks like…here you go.