- Home /
I solved this on my own
Accesing script from newly instantiated game object
Hi guys.So im trying to acces a script form a newly created object.I am creating the player Object at startup and i want enemy object to acces the script from the player object. I was not quite sure how to do this so in the inspector i just put the player prefab. Doing this gave me no errors but the character is not reciving Exp either.
This is the code i have on the enemy script: WarriorObj here is the player prefab but it is not working as i want it too:
PlayerStats StatsScript = WarriorObj.GetComponent<PlayerStats>();
StatsScript.Exp += 20;
Do you use Destroy() before this line, assu$$anonymous$$g you use this when enemy dies?
what im trying to do here is after the enemy has no health left he will then acces the playerstat script and add exp then it will wait and be destroyed after the animation is played and the only thing that does not work is adding the exp and that is because i think it cant acces the WarriorObj variable(since i selected the prefab and not the instantiated player).
Yes, you're right. You need instantiated object and not a prefab GameObject.FindWithTag GameObject.Find
I just tryed : PlayerObj = GameObject.FindGameObjectWithTag("Player");
And i see in the inspector that it still does not find it.
Answer by gcoope · Jul 28, 2014 at 02:05 PM
Try creating a public function in PlayerStats that will increment it's Exp. For example:
public AddExp(int expAmount){
Exp += expAmount;
}
Edit: Forgot to add that you should then call this in the same way you did before, but instead of:
StatsScript.Exp += 15;
Use:
StatsScript.AddExp(15);
im trying to only add exp to the player after the enemy is dead so i need to somehow know when the enemy is dead and i cant just add the enemy in the inspector because im planing to add quite alot of them