- Home /
Instantiate question
Hey,
I have a script that is instantiating other prefabs, however each prefabs needs a different spawn rate, i'd like to store that spawn rate value in each prefabs but i'm not sure how i can access that from the spawner script, i'm sure there is a simple solution to that.
Any suggestions?
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
For example you have class Enemy with a variable.
public class Enemy
{
public float spawnRate;
}
You can access spawnRate variable by using GetComponent<Enemy>().spawnRate;
I know how to get the component of a specific class but the instantiated prefabs all have unique classes, that's why i'm not sure how to do this.
Anyway you could add one more script that has variable you need, but next time use inheritance, make a basic class that has variables that are used in all classes, and then inherit from it. For example:
You have class Fruit
public class Fruit
{
public string name;
public bool eatable;
}
And class Apple
public class Apple : Fruit
{
public string Shape;
}
You can access name by using GetComponent<Fruit>().name;
Answer by hexagonius · Jan 03, 2017 at 10:05 PM
I wanted to throw in that the spawn rate could also be defined in your spawner, side by side with each prefab you want to instantiate. Like this:
public class Spawner : MonoBehaviour {
[System.Serializable]
struct Prefabs{
public GameObject prefab;
public float spawnRate;
}
[SerializeField] Prefabs[] prefabs;
}
you then have as many combinations of GameObject and its spawn rate, without the need of a common base class for the prefabs, which, IMHO, are not responsible for that kind of information.
Thanks, that sounds like a good solution as well, i'll experiment with what has been suggested.