Hello, I am trying to make a UI move when a button is clicked; So I wrote this.
I had already used WaitForSecondsRealtime, but this time it raises “ArgumentException : method return type is incompatible.” when the button is clicked.
I tried with others “WaitFor…” but it did the same…and without the UI doesn’t move (maybe another problem…). Can you help me ?
Thanks.
public IEnumerator SwapRight()
{
if (pos < lim && can_swap)//pos is position of the UI
{
RectTransform avant = lvls[pos - 1];//The UI leaving screen
RectTransform apres = lvls[pos];//The UI coming
can_swap = false;//Only 1 move at the time
while (apres.anchoredPosition.x > 0)
{
avant.anchoredPosition.Set(avant.anchoredPosition.x - v, avant.anchoredPosition.y);//v is speed (p/frame)
apres.anchoredPosition.Set(apres.anchoredPosition.x - v, apres.anchoredPosition.y);
yield return new WaitForFixedUpdate();
}
can_swap = true;
pos += 1;//Update position
}
}
This line
avant.anchoredPosition.Set(avant.anchoredPosition.x - v, avant.anchoredPosition.y);
doesn’t work. anchoredPosition is a property. You can’t use the Set method of the Vector2 value that is return as it won’t change the actual position. You have to assign a vector2 to that property in order to change it. See this question for more information.
In your case the shortest solution is
avant.anchoredPosition -= Vector2.right * v;
// or
avant.anchoredPosition -= new Vector2(v, 0);
The long version would be:
avant.anchoredPosition = new Vector2(avant.anchoredPosition.x - v, avant.anchoredPosition.y);
However that’s less efficient. The most efficient solution is
Vector2 tmp = avant.anchoredPosition;
tmp.x -= v;
avant.anchoredPosition = tmp;
edit
I finally understood your other problem. The UI system can’t directly start a coroutine. So you have to start it yourself:
// assign this method to your UI button.
public void StartSwapRight()
{
if (pos < lim && can_swap)
{
StartCoroutine(SwapRight());
}
}
private IEnumerator SwapRight()
{
RectTransform avant = lvls[pos - 1];//The UI leaving screen
RectTransform apres = lvls[pos];//The UI coming
can_swap = false; //Only 1 move at the time
Vector2 tmpPos1 = apres.anchoredPosition;
Vector2 tmpPos2 = avant.anchoredPosition;
while (tmpPos1.x > 0)
{
tmpPos1.x -= v * Time.deltaTime;
tmpPos2.x -= v * Time.deltaTime;
apres.anchoredPosition = tmpPos1;
avant.anchoredPosition = tmpPos2;
yield return null;
}
can_swap = true;
pos += 1;
}