- Home /
Referencing variables from another script
Hello,
I have a short question. I'm trying to access variable from another script called "weapon":
Everything works good, but when I change weapon (gameObjects with same Tag). I get error:
Is there any way to solve this? I have no idea how.
Thank you.
I re-tagged your question to add it to the list of over 1 million questions about NullReferenceExceptions. (I might have over exaggerated the 1 million.)
Relying on tag is a bad idea, but if you do so then most likely you either put that code not in the right place or you don't call it once again when you switch weapon, or you don't remove the previous one properly, or...can't really guess which one from that part of code.
$$anonymous$$ost likely you just utilize reference to previous "deleted" object, hence the error cose it's null. $$anonymous$$ake sure that there is only one GameObject with tag "Weapon" or alternatively use FindGameObject*s*WithTag and walk through them to find the one you need which != null. Still this is a bad idea to rely on tag.
If you'll not be able to detect more precisely what goes where and why you get null error then be so kind to provide bigger part of your code so that someone can locate what you're missing.
Answer by Graham-Dunnett · Apr 02, 2015 at 07:34 PM
Your code looks up game objects tagged with Weapon. Maybe none are found, in which case your next line is going to go wrong. I suspect that is what is causing the NullReferenceException. Or, maybe the weapons
variable does have a GameObject, but that GameObject doesn't have a weapon component on it. In which case the Debug.Log line will cause a NullReferenceException. As I am sure you'll know from reading all the questions on this site tagged with NullReferenceException
this happens whenever a variable isn't set to a value. You should never assume that a variable is assigned, so check that before using the variable.
Answer by Ugniues · Apr 02, 2015 at 09:24 PM
Found my problem! Thank you! I left parent taged with "weapons". I removed tag and left only on childs, so it works.