Unity Compiler Error not all paths return a value - Object Pooling
So I have the following problem and I am pretty sure it is something super simple but i just can't figured it out.
So in my script I am creating a List of Platforms and Shuffle them to randomize them. And what i want to do is object pooling.
This part of the script should be used to find platforms that arent active and then use them and if there arent any unactive ones it should create a new one.
Now Unity says Assets/Scripts/PlatformPooler.cs(39,20): error CS0161: `PlatformPooler.GetPooledPlatform()': not all code paths return a value
but the way I see it it does always return a value since if there isnt an inactive platform it does instantiate a new one.
Here is my code:
public GameObject GetPooledPlatform ()
{
for (int i = 0; i < pooledPlatforms.Count; i++)
{
if (!pooledPlatforms [i].activeInHierarchy)
return pooledPlatforms[i];
else
{
GameObject obj = (GameObject)Instantiate (platform [i]);
obj.SetActive (false);
pooledPlatforms.Add (obj);
Debug.Log ("Added new Platform");
return obj;
}
}
}
I am pretty sure its just a minor error but I really can't see it. I hope somebody can help. Thanks in Advance.
Answer by HenryStrattonFW · Jan 29, 2017 at 02:33 PM
I'm fairly certain the issue is that whilst your if/else statement covers return calls in each, they are inside a for loop, and therefore a chance that the if/else statement will never get reached (if you pooledPlayforms list is empty for example).
try just putting a "return null;" before the very end of the function, that should clear up the error. It's also a good place to put an error log perhaps letting you know that you've requested a pooledPlatform but don't have one available. Or alternatively have the pool automatically grow when this happens.