Instantiating a gameObject then setting its parent during runtime

I have seen similar questions to this and tried them but they didnt work for me.

I have a simple gui in my demo, when a button is pressed another obstacle is supposed to appear at a random position. Onscreen there are already several obstacles, these are all children of the parent “Obstacles”. I would like to spawn another obstacle when the button is pressed and have it appear underneath Obstacles in the hierarchy. When i try the below code the obstacle is created however it is not a child, just a gameobject on its own.

Instantiate(obstacle, randomPos, Quaternion.identity);

		obstacle.transform.parent = parentObstacles.transform;

I have tried transform.setparent aswell, with the same results.
Is there anything else I can try?
I’m using Unity 5, is this the problem?

You are misunderstanding how to instantiate objects. Unless you know exactly what you’re doing and why, you should:

Expose a myPrefab variable, populated in the inspector…
Never write to or change myPrefab with scripting…
Instantiate the myPrefab object…
Do not treat the new instance as if it’s myPrefab, but an instance thereof…

GameObject prefabInstance = Instantiate( myPrefab, pos, rot ) as GameObject;
prefabInstance.transform.parent = whatever;