Access specifc gameobject position in array

Hello there,
I have an array:

var target : GameObject[]; //the object's target

I get all game objects with same tag and store them in that array. But I can’t get specifc transform position. I tried something like this:

var tpos =  target[1].transform.position;
transform.position = Vector3( Random.Range(tpos.position.x - 10, tpos.position.x +10), transform.position.y,Random.Range( tpos.position.z - 10,tpos.position.z + 10));

But I get errors(when I run game). So all I want is to random position my object, but near specific object in array.Thanks.

I’d first, get an array of all Transforms in the scene, then use a Generic List to create a list of all the Transforms in your scene with a specific tag. Use the list count to create your random index int, then assign a new value each time you fire your code. In this example, I used Vector3.up as my offset, because I used a scene with 10 cubes tagged, then one untagged cube to attach this script to, it will act like your “player”. Each time you press ‘E’, your main cube will end up on top of another randomly picked cube from the list. Hope this addresses your question well enough. You’ll obviously need to replace “YourTag” for this to work.

import System.Collections.Generic;

#pragma strict

private var objectArray : Transform[];
private var objectList : List.<Transform>;
private var objectToMoveTo : Transform;
private var offset : Vector3;
private var index : int;

function Start()
{
	objectArray = GameObject.FindObjectsOfType(Transform);
	objectList = new List.<Transform>();
	for(var t : Transform in objectArray)
	{
		if(t.gameObject.tag == "YourTag")
		{
			objectList.Add(t);
		}
	}
	index = Random.Range(0, objectList.Count - 1);
	objectToMoveTo = objectList[index];
	offset = Vector3.up;
}

function Update()
{
	if(Input.GetKeyDown(KeyCode.E))
	{
		transform.position = objectToMoveTo.position + offset;
		index = Random.Range(0, objectList.Count - 1);
		objectToMoveTo = objectList[index];
	}
}

You are using transform.position = when you need to be referencing the GameObject. Do target[1].transform.position = .