I am trying to instantiate a prefab then access its script and change a variable.
Basically when I kill my monster he instantiates a gold prefab and sets the gold amount based on the monster.
I cant seem to get it to work though I keep getting an error:
Object Reference not set to an instance of an object
at this line
script.goldamount = 10;
This is my code:
if (curhealth < 1){
var thegold = Instantiate(carrygold, transform.position, Quaternion.identity);
var script : gold;
script = thegold.GetComponent("gold");
script.goldamount = 10;
Destroy (gameObject);
}
im really not sure what I am doing wrong ive searched through tons of threads and cant find an answer how to change a variable of instantiated prefab.
Any help is greatly appreciated!
Thanks!
Edit: I thought it could be because the script is in a child of the prefab that I was trying to access so I tried:
var thegold = Instantiate(carrygold, transform.position, Quaternion.identity);
var script2 : gold;
script2 = thegold.GetComponentInChildren("gold");
script2.goldamount = 10;
and still didnt work so I tried:
var thegold = Instantiate(carrygold, transform.position, Quaternion.identity);
var script2 : gold;
go = thegold.transform;
script2 = go.GetComponentInChildren("gold");
script2.goldamount = 10;
and still got the same error that I just did:
Method not found ‘UnityEngine.Transfomr.GetComponentInChildren’