- Home /
Problem is not reproducible or outdated
Swapping gameobjects
I am trying to make a candy crush type game and im looking at changing the position of 2 game objects.What im trying to do is to click a object then click the target object to change the 2 object position between each other.The problem im curently facing is that i can change the target position but the original selected object remains the same.Basicly i can change the target only and not the first object. Here is my code:
if (Input.GetButtonDown ("Fire1")) { Ray ray1 = Camera.main.ScreenPointToRay (Input.mousePosition); if (Physics.Raycast (ray1, out hit, Mathf.Infinity)) { switch (clickCount) { case 2: case 0: originalTile = hit.collider.gameObject; clickCount = 1; break; case 1: targetTile = hit.collider.gameObject; clickCount = 2; break; } Swap(); } } } } void Swap() { var temp = originalTile.transform.position; originalTile.transform.position = targetTile.transform.position; targetTile.transform.position = temp; }
i also keep getting the error that the target tile is not assigned.
i solved it myself the problem was with the position of the Swap call.i inserted it into one of the cases and it worked just like i wanted too.
Answer by SunnySunshine · Mar 03, 2014 at 10:12 AM
You probably need to create a new Vector3. Try this:
void Swap()
{
var temp:Vector3 = new Vector3(originalTile.transform.position.x, originalTile.transform.position.y, originalTile.transform.position.z);
originalTile.transform.position = targetTile.transform.position;
targetTile.transform.position = temp;
}
im getting exactly the same error.Says the original tile was not assigned.seems like its exactly the same
it is swaping them but the problem im getting is that i cannot asign a new original tile.
Answer by Kajal · Sep 20, 2014 at 12:49 PM
try this...it's work for me.Attach this script to your Main Camera.
using UnityEngine;
using System.Collections;
public class planeMove : MonoBehaviour {
int click1 =1;
GameObject originalTile;
GameObject targetTile;
bool t2 = true;
bool t1 = true;
void Update () {
if(Input.GetMouseButtonDown(0))
{
Ray ray=Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit, Mathf.Infinity))
{
switch(click1)
{
case 2:
originalTile = hit.collider.gameObject;
click1= 1;
t1 =false;
break;
case 1:
targetTile = hit.collider.gameObject;
click1 = 2;
t2 = false;
break;
}
if(t1 == false && t2 == false)
Swap(originalTile, targetTile);
}
}
}
void Swap(GameObject org, GameObject tar)
{
Vector3 temp = new Vector3(org.transform.position.x, org.transform.position.y, org.transform.position.z);
org.transform.position = tar.transform.position;
tar.transform.position= temp;
t1 = true;
t2 = true;
}
}
maybe this will help you kajal