c# Get target gameobject from a list

Hi all, first time here and just begin learning scripting. :slight_smile:

I have a script which is instantiated (many times) who need a target (transform).
I tried the code below but makes all scripts use the same target (the first one found).

public GameObject target;   

// Use this for initialization
void Start () {

	target = GameObject.FindGameObjectsWithTag ("Pivot");
}

I also tried using a list but i don’t know how to get another target to each script (it keep choosing the first target).

Another test script with this error (error CS1579: foreach statement cannot operate on variables of type UnityEngine.GameObject' because it does not contain a definition for GetEnumerator’ or is not accessible) :

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class manyTargets : MonoBehaviour 
{
		
		public GameObject target;
		public List<GameObject> pivotTarget;
		
		void Start ()
		{
			
			if (target != null)
			{
				foreach(GameObject go in target)
				{
					pivotTarget.Add(go);
				}
			}
		}
}

I have try from yesterday to make it work with no luck.
I hope i can get some help because i’m out of ideas.
If i’m not to clear, sorry (english is not my first language :slight_smile: ).
Thanks a lot.

If I understand your question correctly, it seems that a static variable may be of good use here. Basically they remain the same wherever your reference them. Create a class like this:

public class Info {
    
    public static GameObject target;

}

and when you need to set a target, use this line in another script:

Info.target = new GameObject(); // Or whatever game object you want the target to be

Doing something with the target (In this example setting position)

transform.position = Info.target.transform.position;

Use this with the first type of script you created. No need for an array. I see people use arrays in so many situations where they are completely unnecessary.