- Home /
Instantiating a prefab and values
Okay, sorry for poor title, I don't know how I would title this. But okay, I have two scripts, but I'm only gonna include some of them, but if you need more of a certain script, feel free to ask. I'm gonna try wording this the best I can because I have a mild form of autism and I have my own way of speaking, so if you also need me to explain with what I mean, feel free to ask as well.
Okay, so I have a game, where if you click the warrior icon, it deducts money and it instantiates a prefab, At the same time, every so often, on the other side of the map there is a enemy that is instantiated.
I have a part of a script that is attached to the enemy, and the script is like this :
private void OnTriggerEnter(Collider other)
{//on trigger enter..
if (other.tag == "Weapon") //if the tag of the collider is "Weapon"
{
Health--; //deduct health
}
And that works. However, below that section of the script, it says this :
if(other.tag == "Player")
{
Health1.DeductHealth();
}
Now in the Health1 Script, more specifically "DeductHealth" it is this :
public void DeductHealth()
{
Health--;
print("Health - " + Health);
}
Now the issue I am having, is instead of removing health from the Warrior that was bought, it removes health from the original prefab, So I was wondering, am I doing something wrong? Is there no way to do this? Or..?
Thanks for reading!
Answer by Suddoha · Feb 19, 2017 at 03:05 AM
You have probably linked your warrior prefab to the enemy prefab via an inspector slot which takes a "Health1" component.
Any enemy that you instantiate will then reference the warrior prefab's Health1 script. What you should do instead is get the reference to the warrior which you've bought / instantiated and get its Health1 component, and last but not least, assign it to the Health1 variable in your enemy's script.
Wouldn't it then get removed if the Warrior dies?
By the way, that was the problem, so thanks on that.
Your answer
Follow this Question
Related Questions
How can I add the OnTriggerEnter function to all game objects that I instantiate? 1 Answer
Hi! How can I use the OnTriggerEnter2D function for the game objects that I instantiate? 3 Answers
PARTICLE SYSTEM NEITHER EMITTING NOR PLAYING (BY SCRIPT) 3 Answers
Distribute terrain in zones 3 Answers
Player sometimes lags and jumps very high when instantiating prefab 1 Answer