Why only one element is displayed by count when the list has 5 elements in it?
I made a list of 5 GameObjects and they are being displayed in the hierarchy(inactive though) and the print statement tells that it has 5 elements.
But when I call the GetPlatform method from another class and print the count of the List, it is displaying only 1 element which thereby, is returning null after one iteration.
Why is it happening so?
public class ObjectPooler : MonoBehaviour {
public GameObject prefab;
public int size;
List<GameObject> plat;
void Start () {
plat = new List<GameObject> ();
for (int i = 0; i < size; i++) {
GameObject o = (GameObject)Instantiate(prefab);
o.SetActive (false);
plat.Add (o);
}
print (plat.Count);
}
public GameObject GetPlatform() {
print (plat.Count);
if(plat.Count>0)
{
GameObject temp= plat[0];
plat.RemoveAt(0);
print ("GetPlatform called");
// temp.SetActive(true);
return temp;
}
return null;
}
public void DestroyPlatform(GameObject obj)
{
plat.Add (obj);
obj.SetActive (false);
}
}
Answer by Lilius · Mar 18, 2018 at 06:30 PM
Its null because you remove the first object from the list and GetPlatform method tries to access first object which is null after first time. Try TrimExcess to get rid of null values: https://msdn.microsoft.com/en-us/library/ms132207(v=vs.110).aspx
public GameObject GetPlatform() {
print (plat.Count);
if(plat.Count>0)
{
GameObject temp= plat[0];
plat.RemoveAt(0);
plat.TrimExcess();
print ("GetPlatform called");
// temp.SetActive(true);
return temp;
}
return null;
}
Hey thanks for the reply.
But the things is I did know why it was returning null.
$$anonymous$$y question was even after filling the list,say, with 5 elements in Start method when I checked the count of the list it is showing only one element is present in the list.
I've already printed the count in Start so I do know that it contains 5 elements for sure. But when I print count in GetPlatform method, it shows only 1 element.
I need help regarding this.
Okay. This answer is completely wrong anyway :) Well your script works fine, just tested. $$anonymous$$aybe theres something wrong in the other class where you call the method GetPlatform? Since it prints count 5 when I tested it.
Hey, sorry for the late reply. You mean the code I wrote is wrong?
GetPlatform is also printing 5 when you tested it?
This is how I'm calling it:
public class Spawner : $$anonymous$$onoBehaviour {
public GameObject op;
ObjectPooler poolerScript2;
float xPos,yPos;
public float xRange=2;
public float y$$anonymous$$in=0.01f;
public float y$$anonymous$$ax= 1;
void Start () {
poolerScript2 = op.GetComponent<ObjectPooler> ();
}
// Update is called once per frame
void Update () {
xPos = Random.Range (-xRange, xRange);
yPos += Random.Range (y$$anonymous$$in, y$$anonymous$$ax);
GameObject platforms = poolerScript2.GetPlatform (poolerScript2.plat);
platforms.transform.position = new Vector2 (xPos, yPos);
platforms.SetActive (true);
}
}