I wanted to accomplish the same thing. This can be done with an additional variable and the OnTriggerExit2D() method.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Driver : MonoBehaviour
{
[SerializeField] float steerSpeed = 1f;
[SerializeField] float moveSpeed = 10f;
[SerializeField] float slowSpeed = 3f;
[SerializeField] float boostSpeed = 20f;
public float oldSpeed;
void Start()
{
oldSpeed = moveSpeed;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Boost")
{
Debug.Log("Boost!");
moveSpeed = boostSpeed;
}
if (other.tag == "Bump")
{
Debug.Log("Bump!");
oldSpeed = moveSpeed;
moveSpeed = slowSpeed;
}
}
void OnTriggerExit2D(Collider2D Bump)
{
Debug.Log("Done bumping!");
moveSpeed = oldSpeed;
}
void OnCollisionEnter2D(Collision2D Bump)
{
Debug.Log("Bump!");
moveSpeed = slowSpeed;
}
void Update()
{
float steerAmount = Input.GetAxis("Horizontal") * steerSpeed * Time.deltaTime;
float moveAmount = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
transform.Rotate(0, 0, -steerAmount);
transform.Translate(0, moveAmount, 0);
}
}
As you can see, I instantiated an arbitrary integer variable called oldSpeed. This was so that I had somewhere to store the speed before entering the trigger changes it. This is demonstrated by the exchange of variables below. Say moveSpeed equals 20f. We store that into the variable oldSpeed. Now, that value is safe, so we can change the moveSpeed variable. Say, moveSpeed = 10f.
oldSpeed = moveSpeed;
moveSpeed = slowSpeed;
So how do we access the default speed? By using oldSpeed! Since it equals 20f.
To return to the default speed provided by the player (in this case, what was provided in the Serialized Field), we need to use an OnTriggerExit2D() function, like so.
void OnTriggerExit2D(Collider2D Bump)
{
Debug.Log("Done bumping!");
moveSpeed = oldSpeed;
}
Thus, upon entering the trigger, the speed is saved as a variable. The trigger changes the speed of the car. Upon exiting the trigger, the speed that was saved to the variable is returned to the car, allowing it to return to the default speed.
… Sorry for saying “speed” a lot, I hope this helped!