Find a transform object with tag.

I am currently using the code below to pick up objects. But I would like it to find the Object1 transform with the “cube” tag and apply each function to it instead of having to repeat the script. I tried Object1 = GameObject.FindWithTag ("cube");, but it didn’t work. The code:

var SpawnTo : Transform; //your hand for example, attack an object to your character that you want the position of what you picked up to go to
var Object1 : Transform; //what your picking up, the object that you want to move
var dist = 5; //distance at which you can pick things up
private var isHolding = false;
 
 
function Update () {
if(Input.GetKeyDown(KeyCode.Q)){ //if you press 'q'
if(Vector3.Distance(transform.position, Object1.position) < dist) //if distance is less than dist variable
{
isHolding = !isHolding; //changes isHolding var from false to true
}
}
 
if(isHolding == true){
Object1.rigidbody.useGravity = false; //sets gravity to not on so it doesn't just fall to the ground
 
Object1.parent = SpawnTo; //parents the object
 
Object1.transform.position = SpawnTo.transform.position; //sets position
 
Object1.transform.rotation = SpawnTo.transform.rotation; //sets rotation
}
else{ //if isHolding isn't true
SpawnTo.transform.DetachChildren(); //detach child (object) from hand
Object1.rigidbody.useGravity = true; //add the gravity back on
}
}

Why didn’t find with tag work? My guess is you didn’t put the .transform afterwards to get it’s transform

Try

Object1 = GameObject.FindWithTag("Cube").transform;

since object 1 is a Transform you have to access the cubes transform property, otherwise your trying to assign a GameObject to Object1, when it should be of type Transform.

You could use a sphere (or any shape) collider to check for close objects, and use the passed Collision object to get the transform of the object that was hit. You will also want some logic to check if the object can be picked up, which can be done by getting the GameObject from the collision, and checking it’s tag.

http://docs.unity3d.com/Documentation/ScriptReference/Collision.html

use:

GameObject.FindGameObjectWithTag(“cube”).transform;

Make sure you are using FindGameObjectWithTag and NOT FindGameObjectsWithTag the plural version.