Problems making something happen local c#

I’m trying to make a game with some random generated elements in it. I’m pretty new in unity and C# therefore it’s properly a beginner problem. It works fine with the objects centered around the world position (0,0,0). But later i want several platforms and therefore i need it to work locally instead(see image)

Pls help :slight_smile:

Here is my code:

public GameObject[] prefab = new GameObject[3]; // number of objects to be placed
    public GameObject[] floraObjects; // The objects to be places
    private int numberOfObjects;
    

    // The min and max positions to spawn the flora in, to keep it inside of the surface
    public float minX = -1;
    public float maxX = 1;
    public float minY = 0;
    public float maxY = 0;
    public float minZ = -1;
    public float maxZ = 1;
    private int i;

    //numbers of objects to create
    public int minObjectSpawning;
    public int maxObjectSpawing;

	// Use this for initialization
	void Start () {

        

        var numberOfObjects = Random.Range(minObjectSpawning, maxObjectSpawing); // create x numbers of objects
        for (int i = 0; i < numberOfObjects; i++)
        {
            int randomObjectFromArray = Random.Range(0, prefab.Length); // Get random object from array
            int randomObject = Random.Range(0, prefab.Length); // get random object
            
            Instantiate(prefab[randomObject], new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), Random.Range(minZ, maxZ)), Quaternion.identity);
            /*Instantiate(prefab[randomObject], new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), Random.Range(minZ, maxZ)), Quaternion.identity);*/
           
        }
    }

To make your objects match the platform, you can do one of two things.

  1. Calculate their world position yourself. If you have some restriction which keeps you from adding a parent to your flora objects, you might have to do this. You would have to add the position of your platform to the randomly generated position you assigned to your flora.

  2. Make your objects the children of the platform where they will be placed. This is the one I would recommend and it is very easy to do. Unity provides a function called SetParent which you can call on your instantiated game objects. It takes two arguments: the parent transform, and a boolean indicating whether to keep the world positioning of your object or translate it to the parent’s coordinate space. To implement this in your code, you would add a call to this function under your Instantiate call.

    GameObject temp = Instantiate(—Your code omitted for brevity—) as GameObject;
    temp.transform.SetParent( whateverYourPlatformObjectIs, false );

By making them children, you could also move your platforms around in the editor after the flora has been placed and the instantiated flora will move with it automatically.