- Home /
I fixed it
How to add something to a list on awake
Hey how do i make my building add itself onto a list there is on another gameobject i just cant seem to find out how. this is my building script where it should add itself on awake
public List<GameObject> buildings;
void Awake()
{
instance = this;
buildings = new List<GameObject>(GameObject.FindGameObjectsWithTag("ListGameObject"));
buildings.Add(gameObject);
}
and this is the lists script it needs to add itself onto
//Lists
public List<GameObject> buildings;
public void Update()
{
//Building List
buildings = new List<GameObject>()
{
};
}
If I understand correctly, you want all objects with the first class to be added onto a list in the second class. I'm no expert with lists, but why are you initializing it in the first class, and not the second one?
okay the thing is that the building is something you can buy so i want it to add itself to the list when it get bought and when it gets destroyed it will remove itself its a way i use to my enemies to find the nearest building to attack and i also want it the other way around so when an enemy spawns it will be added to a enemy list and get the building list and go after the nearest building and when it dies it will remove itself I hope you understand what i mean
Answer by IINovaII · Jan 20, 2020 at 09:06 PM
Try this approach. Create something like a manager class which holds the list of buildings in game.
Manager Class
public class BuildingManager : MonoBehaviour{
private List<GameObject> _allBuildings = new List<GameObject>();
public static BuildingManager Current;
private void Awake(){
if(Current == null)
Current = this;
}
public void AddBuilding(GameObject building){
if(!_allBuildings.Contains(building))
_allBuildings.Add(building);
}
public void RemoveBuilding(GameObject building){
if(_allBuildings.Contains(building))
_allBuildings.Remove(building);
}
}
Sample Building Class which adds itself would look like this.
Building Class
public class Building : MonoBehaviour{
private void Awake(){
BuildingManager.Current?.AddBuilding(this);
}
}
In my opinion, using Hashset ins$$anonymous$$d of List to store Buildings is much better since it won't add duplicates in there.
Okay so this works but i want to have more of the same building but when the building get spawned in its only the first there is getting added to the list how do i make the number 2 and 3 also gets added on the list?
Do all of your building objects have
Building
script attached to it?Is their only one
Building$$anonymous$$anager
object within the scene with theBuilding$$anonymous$$anager
script attached to it?
Right now there is only 1 building but i want to spawn more of this 1 building example it is a orb building and i want to have 3 of them on the same time but only 1 of them gets added and there is only one building$$anonymous$$anager with the buildingmanager script on