- Home /
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?
unityGE$$anonymous$$S.com for beginner explanations of getting objects
Answer by Ninita · Feb 27, 2013 at 08:39 PM
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
Answer by Mikilo · Feb 27, 2013 at 11:39 AM
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?
yes,it is assu$$anonymous$$g that gmO is null but I don't understand why because neither ToClonate or av.avatarsPack or av.avatar are null
If you want to be sure, Debug.Log() right after. And come back to tell me what is written.
So, you've got the answer. XD Set ToClonate and check what happened with avatar's vars.
-.-' both aren't null and problem continue, it assumes gmO like null