Script affecting only a single prefab instance

I’m working on a runner game, and so I have a platform that spawns off screen on the right, then it moves left until it hits a collider, in which it is moved back to the right and continues to move left. It works fine until I add a second platform and attach the script to that new one. It doesn’ matter if I create another platform object or if I make another prefab instance, the problem is still there.

Here is a screen shot of my game. The problem is that the newest platform will be the only one that gets moved. If I were to add more platforms, again, only the newest one will be moved every time the collider is triggered.

Here is the code attached to the trigger collider:

 public bool movePlatformFlag = false;

    void OnTriggerEnter2D(Collider2D coll)
        movePlatformFlag = true;

If it is triggered, the Move Flag will be true.

public class PlatformController : MonoBehaviour
    private Rigidbody2D platformBody;
    private LeftCollider leftColliderScript;

    public float platformSpeed;

	// Use this for initialization
	void Start ()
        platformBody = GetComponent<Rigidbody2D>();
        leftColliderScript = FindObjectOfType<LeftCollider>();
	// Update is called once per frame
	void Update ()
        platformBody.velocity = new Vector3(platformSpeed, 0f, 0f);

        if (leftColliderScript.movePlatformFlag == true)
            leftColliderScript.movePlatformFlag = false;
            transform.position = new Vector3(25f, transform.position.y, -0.1f);

This is the code attached to the platform. In the update function, the platform’s velocity is increased, and if the collider flag is true, then the platform is moved to it’s spawn location.

I’m not sure why the code is affecting only one instance when it should affect each one, and I’m not sure why it’s only the newest one that is affected.

Any help here is appreciated.


Hello, how are you?
What is the expected behaviour? Why do you need a flag in the collider? The code the way it is, the first object to run the Update will be moved once the collision happens, regardless of which one collided, this is probably the problem, seems that the newest gameobject will be ahead in the execution order.
An better design in my opinion would be to withdraw the flag and add an public method MoveToRight in the platform, and whenever the collider gets triggered, you can access the platform that collided with coll.gameObject.GetComponent<PlatformController>().MoveToRight();


Dude, thank you so much, it actually works now!!

I’m still trying to get used to coding in C# and still have habits I used with DarkBasic.

Thanks again!!


Glad for being able to help, whenever we are learning a new framework/software, it is common to encounter this kind of problems :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms