- Home /
Instantiating prefab from another script. Error, prefab is null.
So I have an enemy spawner with a method to instantiate prefabs working just fine. Simplified:
public class EnemySpawner : MonoBehaviour {
public GameObject EnemyPrefab;
public void setEnemies()
{
Instantiate (EnemyPrefab, enemyPos, rotation);
}
void Start()
{
setEnemies();
}
}
This works fine. But it doesnt work when I call it from a different script:
public class Player : MonoBehaviour {
public EnemySpawner enemyspawner;
void Update(){
if (Input.GetMouseButtonDown (0))
{
enemyspawner= new EnemySpawner();
enemyspawner.setEnemies();
}
}
I keep getting this error:
ArgumentException: The prefab you want to instantiate is null.
What am I doing wrong?
Edit: So I figured that I could not create a Monobeaviour by using the New keyword .I changed it to:
enemyspawner = gameObject.AddComponent<EnemySpawner> ();
enemyspawner.setEnemies();
But that still wont work.
Answer by robertbu · Jun 12, 2014 at 07:55 PM
Classes that are derived from MonoBehavior need to be components of objects. You cannot create them with the 'new' keyword. You would have to create a game object and then use AddComponent() to add the script.
Thanks for your response. would you $$anonymous$$d show$$anonymous$$g me an example?
I tried doing this, but it still gives me the same error
enemyspawner = gameObject.AddComponent<EnemySpawner> ();
enemyspawner.setEnemies();
But it is set in the inspector for EnemySpawner. I need to set it for every script that makes that function call as well?