1
\$\begingroup\$

In my game, the player drives a car and when the car reaches the end of the road, I want a different road prefab to be spawned. I have multiple road prefabs, and want to be able to spawn one when the players' Z position is reduced by 7.

Example: Players' Z position is at 7.318 at the start of the game. I want to be able to spawn a different road preset when the cars' Z position has gone down by 7. So at Z = 0, a new road should spawn, then at Z = -7 another road will spawn, ect.. enter image description here

I thought of trying:

 Instantiate(road2, new Vector3(x, x,x), Quaternion.Identity);

but that would just spawn one where I want once, then when the player reaches another point just duplicate a road on top of that.

Currently I don't really have any code for how I can do this, I'm pretty stuck. Perhaps a for-loop might work? How can I do something like this, using some lines of code in my main PlayerController script?

\$\endgroup\$
2
  • \$\begingroup\$ The easy solution would be to just have a local variable that keeps track how many segments you have spawned. Your instantiate would use it and just spawn one at the end and increase the counter by one. It might cause problems in really big worlds, but for smaller parts it should be fine \$\endgroup\$ Commented Apr 11, 2022 at 16:55
  • 1
    \$\begingroup\$ Related, and worth studying: en.wikipedia.org/wiki/Object_pool_pattern \$\endgroup\$ Commented Apr 11, 2022 at 16:56

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.