Object move opposite of its forward movement

Hello This is Mahsa,
I have object let’s call it (A) that moves around , pick random position and move towards it , but i have object (B) too , when object A Detect Object B I want object A move opposite of object B
if it’s not clear comment and I’ll explain more but the point is how make object move opposite of it’s forward direction smoothly

You can try this object controller script on the object A…Let me know it works.

using UnityEngine;

public class ObjectAController : MonoBehaviour
{
    public Transform objectB; // Reference to Object B
    public float movementSpeed = 5.0f;
    public float rotationSpeed = 2.0f;

    private Vector3 targetPosition;

    void Start()
    {
        // Initialize targetPosition with a random position
        targetPosition = GetRandomPosition();
    }

    void Update()
    {
        // Calculate direction towards target position
        Vector3 moveDirection = (targetPosition - transform.position).normalized;

        // Check if Object A detects Object B
        if (Physics.Raycast(transform.position, moveDirection, out RaycastHit hitInfo, Mathf.Infinity))
        {
            if (hitInfo.transform == objectB)
            {
                // Calculate the opposite direction
                Vector3 oppositeDirection = (transform.position - objectB.position).normalized;

                // Smoothly adjust the rotation to face the opposite direction
                Quaternion newRotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(oppositeDirection), Time.deltaTime * rotationSpeed);
                transform.rotation = newRotation;

                // Move in the opposite direction
                transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
            }
            else
            {
                // If Object A doesn't detect Object B, continue moving towards the random position
                // Implement your logic for moving towards the random position here
            }
        }
    }

    Vector3 GetRandomPosition()
    {
        // Implement logic to generate a random target position
        // For example, you can use Random.Range to generate x, y, and z coordinates within a specified range
        return new Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
    }
}