Problem with instantiate in runtime

Hi. I have this code to instantiate some gameobjects in runtime and define one attribute.

public int howMany=3;
public int total=0;
bool loop=true;
public Transform ToClonate;

void Start () {
		GameObject gmO=this.gameObject;
			
		while(loop)
		{
			if(ToClonate)
				gmO=Instantiate(ToClonate,transform.position+OnUnitCircle()*2,Quaternion.identity) as GameObject; 
			else{	
				getAvatars av = this.gameObject.GetComponent ("getAvatars") as getAvatars;
				if(av.avatarsPack!=null && av.avatars!=null)
					gmO=Instantiate(av.avatars[Random.Range(0,av.avatars.Count)],transform.position+OnUnitCircle()*2,Quaternion.identity) as GameObject; 
			}		
			
			followNPC f = gmO.GetComponent<followNPC>();
			if(f==null)
				gmO.AddComponent <followNPC>();
			
			f.enabled=true; 
			f.target=this.gameObject;
				
			total++;			
			if(total==howMany)
				loop=false;
		}		
	}

However, the code crack on first ‘if’ and give me the error

NullReferenceException: Object reference not set to an instance of an object
thisScript.Start () (at Assets/prototypes/grup/thisScript.cs:24).

Anyone can help me with this?

Hi,

if(ToClonate)
     gmO=Instantiate(ToClonate,transform.position+OnUnitCircle()*2,Quaternion.identity) as GameObject;
else{
    getAvatars av = this.gameObject.GetComponent ("getAvatars") as getAvatars;
    if(av.avatarsPack!=null && av.avatars!=null)
        gmO=Instantiate(av.avatars[Random.Range(0,av.avatars.Count)],transform.position+OnUnitCircle()*2,Quaternion.identity) as GameObject;
}
followNPC f = gmO.GetComponent<followNPC>();

In this condition, if ToClonate is null or (av.avatarsPack != null and av.avatars != null), gmO will stay null and an exception will be thrown. Can you check that?

Ok, I found the problem. The problem was the type of variable ToClonate, it must be a GameObject and not a Transform. Now it works very well.
anyway, thanks to whom tried to help me