Hi all,
First post here from someone who is new to Unity and programming. I’m having a lot of fun learning the basics based on a Flappy Bird clone project but I’m stuck with the following seeking some help. Also, I love the forum and the active community. I was able to get much help based on previous threads but not on this one I fear.
In short, I’m trying to have an object move back and forth between two points on the y axis relative to it’s original y position after instantiated. Unfortunately, the original y position gets overwritten with 0 it seems when calling the MoveVertical method (see below please).
First, I’m instantiating prefabs in my scene through a SpawnManager class using a SpawnObstacle method on a random position between two points on the y axis. So far, so good. See code snippet below.
void SpawnObstacle()
{
float lowestPoint = transform.position.y - spawnableDataSO.heightOffsetObstacle;
float highestPoint = transform.position.y + spawnableDataSO.heightOffsetObstacle;
float RandomPointY = Random.Range(lowestPoint, highestPoint);
var spawnPos = new Vector3(transform.position.x, RandomPointY, transform.position.z);
var spawn = Instantiate(spawnObstaclePrefab, spawnPos, Quaternion.identity, parent);
transform.position = spawnPos;
spawn._Spawn(this);
Spawns.Add(spawn);
}
The problem starts when I’m trying to modify the transform.position through a Spawn script which is attached to the prefab that is being instantiated. I’m trying to reference the position where the object has spawned (with Vector3 originalPosition), so I can apply a new Vector3 where y is either a Mathf.Sin or Mathf.PingPong class method with the goal to have the object move back and forth between two points on the y axis relative to it’s initial spawn Position. Both Mathf methods work but the issue is that these are overwriting the original transform.position and it seems that y is declared as 0 instead of the original position. It happens instantly but can be seen nicely when adding a Coroutine where the objects spawns at the desired position on y but once the method (see below please) gets called is being reset to 0 it seems.
In addition, moving the object from right to left works like a charm using transform.Translate.
void MoveVertical()
{
float newY = Mathf.PingPong(Time.time * spawnableDataSO.verticalSpeed, verticalMoveDistance) - verticalMoveDistance / 2;
Vector3 originalPosition = transform.position;
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
}
Any help on this and advice in general would be much appreciated. I guess I’m misunderstanding something fundamentally here.
Thanks so much!
P.S. Here is a quick screenshot of how the scene looks in case this helps visualising it.


