Question by
tpaddock · May 16, 2018 at 10:00 PM ·
c#unity 5script.visual studiolocalscale
transform.localscale to specific size
Thanks in advance for the code help!
Can anyone give me reference to c# script that will scale a gameobject to a specific size and then stop? It is very easy to find a script that scales uniformly but then doesn't stop at a particular x,y,z scale!
Thanks!
Comment
Answer by Vicarian · May 17, 2018 at 01:49 AM
I presume you're scaling in response to some condition? You can use a coroutine with a lerp or slerp to accomplish that:
using System.Collections;
using UnityEngine;
public class LerpScale : MonoBehaviour {
[SerializeField] float m_lerpTime = 6f;
[SerializeField] Vector3 m_targetScale;
Coroutine m_coroutine;
float m_timeInterval, m_timeElapsed;
void Start() {
m_coroutine = null;
m_timeElapsed = 0;
}
void Update() {
// Stow the coroutine reference to make sure you don't activate this multiple times
if (Input.GetKeyUp(KeyCode.R) && m_coroutine == null)
m_coroutine = StartCoroutine("ScaleObject");
}
void FixedUpdate() {
m_timeInterval = Time.deltaTime;
}
IEnumerator ScaleObject()
{
float inc;
inc = m_targetScale.magnitude / m_lerpTime * m_timeInterval;
Debug.Log("Coroutine started");
while (m_timeElapsed < m_lerpTime)
{
transform.localScale = Vector3.Lerp(transform.localScale, m_targetScale, inc);
m_timeElapsed += m_timeInterval;
yield return null;
}
transform.localScale = m_targetScale;
StopCoroutine(m_coroutine);
m_coroutine = null;
Debug.Log("Coroutine stopped");
}
}