- Home /
Instantiating Prefabs from a MonoBehaviour-derived class using an array -> compiling but not rendering [SOLVED]
Hey guys, so i thought i'd spawn 4 controllable characters (in the code snippet i named them players, sry for the inconvenience) for 2 different players. I try to instantiate them in my GameManager's for-loop, but they don't spawn neither in the game nor are listed in the hierarchy. Before going any further, here is the code:
public HumanPlayer[] prefabPlayer1;
public HumanPlayer[] prefabPlayer2;
private void Awake()
{
prefabPlayer1 = new HumanPlayer[4];
prefabPlayer2 = new HumanPlayer[4];
SpawnPlayerOne();
SpawnPlayerTwo();
}
private void SpawnPlayerOne()
{
for(int i = 0; i < prefabPlayer1.Length; i++)
{
//creating new Player for the user (i times)
prefabPlayer1[i] = new HumanPlayer();
prefabPlayer1[i].SetPlayerType(i);
Instantiate(prefabPlayer1[i], new Vector3(i,2,i), Quaternion.identity);
}
}
private void SpawnPlayerTwo()
{
for(int i = 4; i < 8; i++)
{
prefabPlayer2[i%4] = new HumanPlayer();
prefabPlayer2[i%4].SetPlayerType(i%4);
Instantiate(prefabPlayer2[i%4], new Vector3(i,2,i), Quaternion.identity);
}
}
note that HumanPlayer is a class derived from my abstract PlayerScript class (that's derived from MonoBehaviour). VS2017 doesn't show me any errors on this code. Also the HumanPlayer script is attached to my Player prefab (which also has a MeshFilter and MeshRenderer) and the GameManager is tied to an "Empty" in my scene (that's also active ofc). My GameManager shows me the following arrays:
i thought the "None" only means, they got no specific name assigned to them. However since they don't spawn at all, i dunno.
Try something like prefabPlayer1[i] = Instantiate(new HumanPlayer, new Vector3(i,2,i), Quaternion.identity)
this didn't resolve the issue :( however it's a much cleaner way to write it, so i changed it, ty :)
$$anonymous$$aybe it has something to do with your HumanPlayer class? Are there any other parameters the Constructor could take? Is HumanPlayer a gameObject/prefab? If not try instantiating a new gameObject and adding the HumanPlayer script. example:
public GameObject[] prefabPlayer1;
//...
...//
private void SpawnPlayerOne()
{
for(int i = 0; i < prefabPlayer1.Length; i++)
{
//creating new Player for the user (i times)
prefabPlayer1[i] = Instantiate(new GameObject(), new Vector3(i,2,i), Quaternion.identity);
prefabPlayer[i].AddComponent<HumanPlayer>();
HumanPlayer pS = prefabPlayer[i].GetComponent<HumanPlayer>();
pS.SetPlayerType(i);
}
}