How to Automatically Move objects?

I’m having trouble making my object automatically move from right to left when it collides with a wall or another object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class autoMove : MonoBehaviour
{
    public float speed = 3.0f; // adjust the speed to your liking
    private bool movingRight = true; // initial direction
    private bool movingLeft = true;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        if (movingRight)
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }
        else 
        {
            transform.Translate(Vector3.left * speed * Time.deltaTime);
        }
    }
    private void OnTriggerEnter2d(Collider2D other)
    {
        movingRight = false;
    }
}

When it collided with a wall, it doesn’t move in the opposite direction. How do I fix this?

Sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

It should be OnTriggerEnter2D, upper case D.

1 Like

As said, it’s “OnTriggerEnter2D” as per all the docs. C# is case-sensitive.

Also, you should never modify the Transform when using 2D physics. 2D physics not a renderer, the only thing that moves is a Rigidbody2D and you should use its API to cause movement, colliders are attached to them. The Rigidbody2D then writes to the Transform.

If you need any more information then please look at the documentation or look at some tutorials on 2D physics movement.