How to ignore these missing elements?
or
How to remove my destroyed target from the list?
public class SkinMananger : MonoBehaviour {
public GameObject[] characters;
public int selectedCharacter = 0;
public GameObject carrot;
public void NextOption()
{
characters[selectedCharacter].SetActive(false);
selectedCharacter = (selectedCharacter 1) % characters.Length;
characters[selectedCharacter].SetActive(true);
}
public void BackOption()
{
characters[selectedCharacter].SetActive(false);
selectedCharacter--;
if(selectedCharacter < 0)
{
selectedCharacter = characters.Length;
}
characters[selectedCharacter].SetActive(true);
}
public void PlayGame()
{
PlayerPrefs.GetInt("selectedCharacter", selectedCharacter);
}
}
and I use Destroy(gameObject); for my characters when certain actions take effect. So I need a skin manager to work also when they are destroyed. As at this moment, it stuck.
CodePudding user response:
You can use Linq Where
and the implicit bool
operator like e.g.
using System.Linq;
...
public void RemoveInvalidEntries()
{
characters = character.Where(c => c).ToArray();
}
This basically equals doing something like
var list = new List<GameObject>();
foreach(var c in characters)
{
if(c) list.Add(c);
}
characters = list.ToArray();
Alternatively I usually prefer a dedicated class that keeps track of existing instances itself like e.g.
public class Character : MonoBehaviour
{
private readonly static List<Character> instances = new List<Character>();
public IReadOnlyList<Character> Instances => instances;
private void Awake ()
{
instances.Add(this);
}
private void OnDestroy ()
{
instances.Remove(this);
}
}
so later you can go through
Character.Instances
and be sure that in that list always only currently existing instances are registered.