- Home /
Getting Vector3 from random item in List
Hi, New to C# and be stuck on this for a couple of nights. Trying to find a way to get transform info from a item randomly selected from an List. Had originally tried using an Array, but had read that using Lists were better suited.
Ultimately I want to be able to attach this script to a cube and have it Lerp quickly it between moving targets in my scene. Any help would be appreciated.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class focusChaser3 : MonoBehaviour { public List targets = new List();
void Start()
{
foreach (GameObject item in GameObject.FindGameObjectsWithTag("targetEye"))
{
targets.Add(item);
}
var targRan = Random.Range(0, targets.Count);
Debug.Log(targets[targRan]);
transform.position = new Vector3(targets[targRan].transform);
}
}
Answer by AlwaysSunny · May 15, 2017 at 11:52 PM
Always format pasted code with the 101010 button.
You seem to have a handle on how to grab your random element, but you don't appear to be making use of it correctly. Perhaps you wanted:
transform.position = targets[targRan].transform.position;
Your answer
![](https://koobas.hobune.stream/wayback/20220612122059im_/https://answers.unity.com/themes/thub/images/avi.jpg)