我从Unity开始,想要开始使用一些概念。基本上我想要做的是:如果我点击屏幕的右侧,切换蓝色和黄色框的位置,如果我随后点击屏幕的右侧,则用红色框切换黄色框。我已经为屏幕的左侧和右侧设置了画布。我需要做什么?
[编辑]:我可以在图片中看到我所遇到的错误。我不确定我是否应该采用不同的方法来解决这个问题。任何建议将不胜感激!
答案 0 :(得分:0)
将其添加到按钮并设置对象引用:
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class SwapObjectPositions : MonoBehaviour {
public Transform transformA;
public Transform transformB;
void Start () {
GetComponent<Button>().onClick.AddListener(SwapPositions);
}
public void SwapPositions()
{
if (transformA==null || transformB==null)
{
Debug.Log("Set object references in the inspector please");
return;
}
Vector3 posA=transformA.position;
transformA.position=transformB.position;
transformB.position=posA;
}
}
答案 1 :(得分:0)
The problem is that you have 3 boxes that switch places, not just two. After the first swap the order change. You must make something like that :
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class SwapObjectPositions : MonoBehaviour
{
public Transform[] boxTransform;
public Button LeftButton;
public Button RightButton;
void Start()
{
if (LeftButton == null || RightButton == null)
{
Debug.Log("Button reference missing");
}
LeftButton.onClick.AddListener(LeftSwap);
RightButton.onClick.AddListener(RightSwap);
if (boxTransform.Length != 3 || boxTransform[0] == null || boxTransform[1] == null || boxTransform[2] == null)
{
Debug.Log("Boxes reference missing");
}
}
public void LeftSwap()
{
// Swap Positions
Vector3 tempPosition = boxTransform[0].position;
boxTransform[0].position = boxTransform[1].position;
boxTransform[1].position = tempPosition;
// Swap Transform
Transform tempTransform = boxTransform[0];
boxTransform[0] = boxTransform[1];
boxTransform[1] = tempTransform;
}
public void RightSwap()
{
// Swap Positions
Vector3 tempPosition = boxTransform[1].position;
boxTransform[1].position = boxTransform[2].position;
boxTransform[2].position = tempPosition;
// Swap Transform
Transform tempTransform = boxTransform[1];
boxTransform[1] = boxTransform[2];
boxTransform[2] = tempTransform;
}
}