Glytchy
1
I am trying to create a GameObject to serve as a manager for a match in my game. One of the jobs I want to to do is to create all of the Planets that will exist during the match and store them in a List so that my objects that need to run gravity calculations can reference each item in the list to find the total force on them. I have a script, LocalGravityAttractor, that all Planet scripts have as a required component. However I want the list to be of LocalGravityAttractor and not of Planet so that later in development I can generate new attractors that are not planets. I have a Prefab Planet that should be used to generate planets. How can I instantiate them and add them to the list?
Currently I have:
public class MatchManager : MonoBehaviour {
public Planet planetPrefab;
public uint maximumAttractors = 1;
public List<LocalGravityAttractor> stageAttractors;
// Use this for initialization
void Start () {
//create planets
stageAttractors = new List<LocalGravityAttractor>();
stageAttractors.Add((LocalGravityAttractor)Instantiate(planetPrefab));
}
}
But I get an error that I can’t cast a Planet to a LocalGravityAttractor.,
I think this should work
stageAttractors.Add(Instantiate(planetPrefab).GetComponent<LocalGravityAttractor>());
Glytchy
3
Thank you. That seems to have worked, I had to change the prefab reference to be a GameObject instead of a Planet though (to assign the prefab in the editor, which eventually I don’t want to do). I ended up with this:
public class MatchManager : MonoBehaviour {
public GameObject planetPrefab;
public uint maximumAttractors = 1;
public List<LocalGravityAttractor> stageAttractors;
// Use this for initialization
void Start () {
//create planets
stageAttractors = new List<LocalGravityAttractor>();
stageAttractors.Add(Instantiate(planetPrefab).GetComponent<LocalGravityAttractor>());
}
}
which seems to be working. Am I right in asusming that is is storing only a reference to the Planet’s LocalGravityAttractor component in the list and NOT a reference to the planet that was created?