For my game, I need to have 3 sets of wall on each players side of the screen that are each moving upwards and reappearing from the bottom of the screen once they reach the top and go off screen.
I have figured out how to do this with one of the sets of walls. However, my current method would require me to type the same thing many time over again in the script but with slightly different numbers for each of the different positions.
So what I’m wondering is there a simpler way for my to have my wall go off screen and come back up on the opposite Y-axis? Preferably a way that does not need me to type the exact position for each of the sets of walls.
Here is what I’m currently using in my wall script at the moment:
void CalculateMovement()
{
transform.Translate(Vector3.up * _speed * Time.deltaTime);
if (transform.position.y > 6f)
{
transform.position = new Vector3(6.42f, -6, 5.996884f);
}
When you say 3 sets of walls, what do you mean by a “set”? Because now you have one wall move off the top and then reappear in another y location coming up from the bottom. Is that one set?
Do your wall “sets” - what ever those are - to appear in predetermined locations? If so, you can formulate an offset for each set, so that you only need to hard code the position for one set, and then add the offset to get the positions of the other sets.
Then instead of having a separate script for each set of walls, create a controller script that passes the move function and a reference current wall set to your move function, along with an index to which wall set is being moved.
It would probably be better to create an array of objects that holds a reference to each wall set.
So some pseudo code:
public GameObject wallPrefab; // drag your prefab to this inspector property
private GameObject[] wallsets;
private float yOffset = 10f; // for example
private int maxWallSets = 3;
private Vector3 startWallPos = new Vector3(6.42f, 6f, 5.996884f); //example
void Start() {
wallsets = new GameObject[ maxWallSets ];
for( i = 0 through maxWallsets ) {
Vector3 nextWallSetPos = startWallPos;
nextWallSetPos.y += i * yOffset;
wallSets[ i ] = intantiate your prefab here using nextWallSetPos
}
}
void Update() { // assuming you move everything in the update loop
for( i = 0 through maxWallsets ) {
CalculateMovement( wallSets[ i ] , i ) {
}
}
void CalculateMovement( GameObject g, int i ) {
g.transform.Translate(Vector3.up * _speed * Time.deltaTime);
if ( g.transform.position.y > 6f) {
Vector3 nextWallSetPos = startWallPos;
nextWallSetPos.y = -nextWallSetPos.y + i * yOffset;
g.transform.position = nextWallSetPos;
}
}
That’s the gist of one approach. Probably needs some tweaking and fixing of course - that’s a very quick look.