- Home /
[C#] List.Count keeps returning 0
Hi,
I have the script WaypointsScript.cs
attached to an empty object. This empty object has several children. I import a list of children objects to my script CameraMove.cs
. Inside CameraMove.cs
I need to use List.Count to get some stuff done, but when I use List.Count it always returns 0. I know the list gets imported because I can still use items within the list.
The code from WaypointsScript.cs
public class WaypointsScript : MonoBehaviour {
public List<GameObject> children = new List<GameObject>();
// Use this for initialization
void Start () {
foreach (Transform child in transform) children.Add(child.gameObject);
}
// Update is called once per frame
void Update () {
}
}
And this is the relevant code from CameraMove.cs
public List<GameObject> listOfChildren = new List<GameObject>();
public float waypointAmount = 0;
// Use this for initialization
void Start ()
{
WaypointsScript WPS = (WaypointsScript)GameObject.Find("Waypoints").GetComponent("WaypointsScript");
listOfChildren = WPS.children;
waypointAmount = WPS.children.Count;
}
waypointAmount should be the amount of entry's in the list, but this always returns 0.
If I make waypointAmoun = listOfChildren.Count;
this also returns 0, but if I acces the objects in the list it works.
What is happening, and what am I doing wrong?
Answer by Berenger · Jun 04, 2012 at 03:36 PM
The problem is the order the Start function are called. Here, CameraMove.Start seems to be called before WaypointsScript.Start.
Three options there. Either you specifie to Unity that WaypointsScript must call Start first (Edit->Project Settings->Script Execution order), or you declare Awake instead of Start in WaypointsScript, or finally you can use a public function called Init (or whatever) which is called by the camera right after the Find function.
$$anonymous$$akes sense that the order is important. Putting the foreach (Transform child in transform) children.Add(child.gameObject); in void Awake () solved it! Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613072337im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
List<> Size Changes Without Removing Elements 1 Answer
Generic List.Count always gives 0 2 Answers
Accessing base class list in a derived class. 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers