Hi @yellowyears best way I can think making your object changing position over time is using Coroutines since they fit nicely with Lerp. Alternatively you could have a check in the Update function, and use it to get some movement. Try:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModularAppliance : MonoBehaviour
{
[Range(0, 3)]
public int _requestedAppliance = 0;
[SerializeField]
private GameObject[] _appliances; // Create a reference to the prefabs.
private GameObject current_appliance;
private Vector3 distance_to_lerp = new Vector3 (0, 10, 0);
private int frames_to_lerp;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ChangeAppliance();
}
}
private void ChangeAppliance()
{
switch (_requestedAppliance)
{
case 0:
// Game object (appliance) 1 is requested.
current_appliance = Instantiate(_appliances[_requestedAppliance], transform.position, Quaternion.identity);
// Lerp code goes here.
frames_to_lerp = (int) (distance_to_lerp.magnitude / Time.fixedDeltaTime) + 1; //+1 used to round the float up
StartCoroutine(Lerp_to_Position(current_appliance, frames_to_lerp));
break;
}
}
IEnumerator Lerp_to_Position(GameObject current_appliance, int frames_to_lerp)
{
Vector3 start_position = current_appliance.transform.position;
Vector3 end_position = start_position + distance_to_lerp;
// Here we 'queue' up some changes in position, and they execute after a small delay
for (int i = 0; i < frames_to_lerp; i++)
{
yield return new WaitForSecondsRealtime(Time.fixedDeltaTime);
current_appliance.transform.position = Vector3.Lerp(start_position, end_position, Time.fixedDeltaTime * i);
}
}
}
Also you can choose any position to lerp to using Vector3’s that way. Makes sense to give you the freedom. You can also use Vector2.Lerp for 2D movement, and Mathf.Lerp for 1D.