New2GameDev – Array of Prefabs

Updated on May 16, 2017 in [A] Tutorials
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on Reddit0
2 on May 16, 2017

Hi, guys :) I’m new to Unity and C# programming. Recently, I’ve been working for my senior project wherein the user must catch a ball that corresponds on what he needs. The balls spawn with the same as fruit ninja. I have 10 prefabs but I only instantiate 4 of them during start. If the user catches the correct ball for at least 3 times, I want to remove that specific ball from the first 4 prefabs (making only 3 left) then adding 1 prefab from the remaining set (during start, 4/10 prefabs are instantiated, making it only 6 left). Hope you can help me guys:)

  • Liked by
Reply
0 on May 16, 2017

You could have two arrays, one for the first 4 (primary) and the second for 6 other prefabs (secondary).

public GameObject [] primary;
public GameObject [] secondary;

I don’t know how you plan to implement removing a specific prefab from the array and what’s your setup like, but here is a little help:

public void ReplaceArray(GameObject prefab)
{
    for (int i = 0; i < primary.Length; i++)
    {
        if (prefab == primary [i])
        {
            primary [i].gameObject.SetActive (false);
            // Replace the gameObject with the first one from the secondary array
            primary [i] = secondary [0];
        }
    }
}
  • Liked by
Reply
Cancel
0 on May 16, 2017

Removing elements from an array is possible but in my opinion not the best way to do it. Arrays aren’t dynamic this means that you can change the value of a specific value in the array you can’t change the length of one (adding or removing values) or at least not without redefining the array.

If you are however required to have the ability to change the length I’d recommend using a List

  • Liked by
Reply
Cancel