I want to make this 2d ui move up and down really fast. I tried so many variations of this code, and I gave up here:
while (true)
{
transform.Translate(transform.up * 100);
yield return new WaitForSeconds(0.1f);
transform.Translate(-transform.up * 100);
}
All this does is change y to -90 and leaves it there. Nothing else. What am I doing wrong?
To elaborate, I have tried SO MANY variations, like transform.position = , transform.Translate(0,x,0) etc
We need to see more code - the context where you’re calling this is important. If you’re calling this from Update, that’s a problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scareone : MonoBehaviour
{
private void OnEnable()
{
StartCoroutine("move");
}
private void Start()
{
StartCoroutine("move");
}
IEnumerator move()
{
while (true)
{
GetComponent<RectTransform>().anchoredPosition = new Vector3(0,-90,0);
yield return new WaitForSeconds(1f);
GetComponent<RectTransform>().anchoredPosition = new Vector3(0, 90, 0);
}
}
}
No, im not calling from update.
Oh my god, Im such an idiot. I just needed to add another ‘wait’ at the end of the loop, because like this it just kept adding 90, then instantly taking it away, making it appear as though nothing changed. Here is the working code:
IEnumerator move()
{
while (true)
{
GetComponent<RectTransform>().anchoredPosition = new Vector3(0,-90,0);
yield return new WaitForSeconds(1f);
GetComponent<RectTransform>().anchoredPosition = new Vector3(0, 90, 0);
yield return new WaitForSeconds(1f);
}
}
Thanks anyway.