Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

I want to repeat my ground with the positoin of my player.

Discussion in 'Scripting' started by shez561, Apr 27, 2020.

  1. shez561

    shez561

    Joined:
    Sep 19, 2019
    Posts:
    20
    Hi,

    I am working on my first game which is an endless car racing and since I am new I face difficulty in writing the perfect codes.

    As per the attachment, I need help to repeat my ground which consist of 2 platforms and every time when my player crosses the first platform I want the same to start over at the end of second platform.
    Actually I have pretty much done that and the platform repeating itself but I actually want my player to repeat that platform for me rather than platform repeating itself.

    Please help me in writing the correct code that when my player hit the second platform the first platform should repeat at the end of second platform.

    Scene.png

    Script.png
     
  2. Leonetienne500

    Leonetienne500

    Joined:
    Dec 5, 2016
    Posts:
    130
    What you are talking about is a chunk system, like in minecraft for example.
    The spawning/despawning of those chunks is not difficult.

    The difficult part is getting them to line up properly, to not spawn multiple at the same position and to despawn the ones out of reach.

    You should give these platforms consistent dimensions. In minecraft EVERY chunk is 16x16 blocks big. They should also be square.

    Vector3 chunkSpace = worldSpace / chunkWidth; //You must also truncate to closest smaller int



    That way you can "easily" convert world space to chunk space. Like, Vector3(0, 0, 0) would be your position of the first chunk in chunk space and Vector3(0, 0, 1) of your second chunk.

    This is not that simple that someone could post "the perfect code" for your project. It depends a lot on how your project is set up.

    Otherwise... heres how you can instantiate a prefab (like your chunk)
    Code (CSharp):
    1. GameObject newChunk = GameObject.Instanciate(yourPrefab, null); //yourPrefab being a public GameObject
    2.  
    3. newChunk.position = yourNewChunksPosition; //e.g. chunkSpacePosition * chunkWidth
     
    Last edited: Apr 27, 2020
  3. shez561

    shez561

    Joined:
    Sep 19, 2019
    Posts:
    20


    Sir I actually don't want my platform to instantiate every time by a new vector3 by itself. I want my player hit the second platform then the first platform should repeat.
     
  4. Leonetienne500

    Leonetienne500

    Joined:
    Dec 5, 2016
    Posts:
    130
    Why not just supply three or four chunk variants as prefabs and choose one at random when instantiating?