Instantiate Object At Local Position

This question is kind of continued from this one:

I can instantiate an object to local space and it works with the following code:

private void AddGoalStalker()
    {
        GameObject goalStalker = Instantiate(goalStalkerPrefab, hazardDirectory, false) as GameObject;
        Vector3 pos = new Vector3(hole.transform.position.x, goalStalker.transform.position.y, hole.transform.position.z);
        goalStalker.transform.position = pos
    }

However, the below code doesn’t work even though it’s essentially doing the same thing?

private void AddGoalStalker()
{
    Vector3 pos = new Vector3(hole.transform.position.x, goalStalkerPrefab.transform.position.y, hole.transform.position.z);
    InstantiateObject(goalStalkerPrefab, hazardType.GoalStalker, pos);
}

private void InstantiateObject(GameObject prefab, Hazard hazard, Vector3 pos)
{
    GameObject obj = Instantiate(prefab, hazardDirectory, false) as GameObject;
    float rot = RandomRot(hazard);
    obj.transform.position = new Vector3(pos.x, pos.y, pos.z);
    obj.transform.Rotate(Vector3.up, rot, Space.Self);
}

Does anyone know why this doesn’t work? I need to do it the second way for additional checks in the InstantiateObject() method that won’t affect the positioning.

Any help will be really appreciated

goalStalkerPrefab.transform.position is not the same as goalStalker.transform.position. Try changing the line where you set the position to obj.transform.position = new Vector3(pos.x, obj.transform.position.y, pos.z);.
**
goalStalkerPrefab looks at the actual prefab object (probably has a y value of 0), while goalStalker.transform.position is looking at the copy of the prefab that you have spawned in your scene which (I believe) will have the same Y value as your “hazardDirectory” since you are spawning it as a child of that.

Thanks for the help @unity_ek98vnTRplGj8Q , the changes worked! Below is the new, working code :slight_smile:

private void AddGoalStalker()
{
    Vector3 pos = new Vector3(hole.transform.position.x, goalStalkerPrefab.transform.position.y, hole.transform.position.z);
    InstantiateObject(goalStalkerPrefab, hazardType.GoalStalker, pos);
}

private void InstantiateObject(GameObject prefab, Hazard hazard, Vector3 pos)
{
    GameObject obj = Instantiate(prefab, hazardDirectory, false) as GameObject;
    float rot = RandomRot(hazard);
    obj.transform.position = hazardDirectory.position + pos;
    obj.transform.Rotate(Vector3.up, rot, Space.Self);
}