Adding to a public list from a script on another object.

I’m trying to add to a public list from a script on another object. Eventually I want to have spawned units to be entered into a list so I can store which units are spawned in what order. This seems really simple, can anyone help?

This is the public list:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
      public class ExampleLister : MonoBehaviour 
        {
        			public List<GameObject> FriendlyUnitsOrder;
        	void Start ()
        	{	
        			FriendlyUnitsOrder= new List<GameObject>();
        	} 
        	
        }

This is the the script on the object I will eventually turn into a unit:

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

public class Unit_Default_Friendly : MonoBehaviour 
{
	void Start () 
	{
		gameObject.GetComponent<Mover>().FriendlyUnitsOrder.Add(this.gameObject);
	}
	

}

Thanks in advance for any help.

Hi,
The class containing the List doesn’t need to be a monobehaviour, and having it be monobehaviour will only make it more complicated.

Try this:

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

public class ExampleLister
{
	private static ExampleLister lister;
	private static List<GameObject> FriendlyUnitsOrder;

	public static List<GameObject> getList(){
		if (FriendlyUnitsOrder==null){FriendlyUnitsOrder=new List<GameObject>();}
		return FriendlyUnitsOrder;
	}

	public static void Add(GameObject go){
		if (FriendlyUnitsOrder==null){FriendlyUnitsOrder=new List<GameObject>();}
		FriendlyUnitsOrder.Add (go);
	}
}

You can then use the commands

ExampleLister.Add(newunithere);

and

ExampleLister.getList();

to interact with it.

This is not an ideal solution, but it should get you started.