var hit : RaycastHit;
var noObj : Transform = null;
var switchObj : Transform = null;
var tempObj : Transform;
function Update()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Input.GetMouseButtonDown (0))
{
if(!noObj)//no object picked yet
{
if (Physics.Raycast (ray, hit, 100))
{
noObj = hit.transform;//save picked objects transform
tempObj.transform.position = noObj.transform.position;
}
}
if(noObj !=null)//if noObject now has a transform
{
if (Physics.Raycast (ray, hit, 100))
{
switchObj = hit.transform;
DoTheSwitch();
}
}
}
}
function DoTheSwitch()
{
noObj.transform.position = switchObj.transform.position;//moves the first clicked object to the second clicke objects position
switchObj.transform.position = tempObj.transform.position;
}
an else between your ifs, so you are not using the clicked object as first AND second object.
clearing noObj after the switch for the next click
tmpObj should be a Vector3
function Update()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Input.GetMouseButtonDown (0) && Physics.Raycast (ray, hit, 100))
{
if(!noObj)//no object picked yet
{
noObj = hit.transform;//save picked objects transform
tempObj = noObj.transform.position;
} else if (noObj !=null) { //if noObject now has a transform
switchObj = hit.transform;
DoTheSwitch();
}
}
}
function DoTheSwitch()
{
noObj.transform.position = switchObj.transform.position;//moves the first clicked object to the second clicke objects position
switchObj.transform.position = tempObj;
noObj = null;
}
(I also shortened it a bit, but that doesn’t change the logic)
What happens when you run your test code? It looks like you are missing a line in your DoTheSwitch function to assign the noObj position to tempObj before moving it. I think it needs to be
function DoTheSwitch()
{
tempObj.transform.position = noObj.transform.position; //Cache the position of noObj before moving it
noObj.transform.position = switchObj.transform.position;//moves the first clicked object to the second clicke objects position
switchObj.transform.position = tempObj.transform.position; //move the second object to the cached position of the first object
}
It is because the tempObj Transform object is never created, you need to either change tempObj to Vector3 or Instantiate the tempObj before setting the position.