- Home /
C# Make array based on script variable
Thank you for reading my question. I have a number of objects that have a script on them called "SpawnPoint" that have a few variables including "Team ID." I am trying to make an array of only objects that both have the Spawn Point script attached, and have the Team ID variable set to 0.
I can make an array of all Spawn Points by:
SpawnPoint[] spawnPoints;
void Start () {
spawnPoints = GameObject.FindObjectsOfType <SpawnPoint>();
}
But that is as far as I can get. Any help would be greatly appreciated.
Answer by Uraani · Apr 04, 2014 at 06:15 PM
This is just how i'd do it:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpawnPoint : MonoBehaviour
{
//static list for the spawnPoints
public static List<SpawnPoint> spawnPoints = new List<SpawnPoint> ();
//assuming its an integer
public int teamID;
// Use this for initialization
void Start ()
{
spawnPoints.Add (this);
}
void OnDestroy()
{
spawnPoints.Remove (this);
}
public static SpawnPoint[] GetTeamIDSpawns(int ID)
{
List<SpawnPoint> teamPoints = new List<SpawnPoint> ();
foreach(SpawnPoint spawnPoint in spawnPoints)
{
if(spawnPoint.teamID == ID)
{
teamPoints.Add(spawnPoint);
}
}
return teamPoints.ToArray ();
}
}
pass the searched ID value in the parameters in this case its 0
How to use it:
//this gets all SpawnPoints with teamID of 0
spawnPoints = SpawnPoint.GetTeamIDSpawns(0);
Thanks man! That did the trick. Is there a way to check two variables? I have a bool called "isSeen" where if a character is looking at a spawn point, isSeen becomes true. I know, I'm asking a lot. Thanks either way!