ArgumentException: The prefab you want to instantiate is null.

Hey guys,

I’m running into a problem. I have a script which instantiates a prefab, like this:

public class SegmentScript : MonoBehaviour {

 public GameObject bar_piece;
 private int start_height;
 private int end_height;
 private int score;
 private GameObject[] pieces;
 private Vector3 start_location;
 
 // Use this for initialization
 public void Start () {
 
 pieces = new GameObject[10];
 
 AddPieces(start_height, end_height);
 }
 
 public void AddPieces(int start, int end){
 
 for(int i = start;i<end;i++){
 Vector3 piece_location = start_location;
 piece_location.y = i;
 
 GameObject new_piece = Instantiate(bar_piece, piece_location, Quaternion.Euler(0,0,0)) as GameObject;
 pieces *= new_piece;*

}
}
}
Now, when I select the script in the inspector, I can drag and drop a prefab to the bar_piece slot. During runtime, I add this script through another script using the AddComponent function.
But somehow the prefab slot for bar_piece is empty again and I get the ArgumentException.
The weirdest part is that another script uses the exact same method to instantiate an object, but that works fine.

AddComponent will not copy linked objects to this component. it just adds an empty component. if you want to save link you should:

  1. add component in editor window
  2. attach all links you need to this component
  3. save gameobject with component to a prefab
  4. instantiate this prefab in runtime

second solution:

right after AddComponent attach all objects also in script like this:

addedComponent.someLinkToPrefab = this.someLinkToPrefab;