- Home /
Changing a bool on only 1 instance of a prefab instead of all?
So I am creating this little weapon shop that just spawns a prefab'd gun when you buy it, which then you can go up to it and equip it. The problem I am having is I have it so that way the weapon only shoots if you have it in your hand, which is controlled by a bool. The issue I have is when there are 2 instances of one weapon in the scene, which, when I equip one gun, it changes the bool for both, making it so the weapon can't shoot. I was wondering what I would have to do to specify that only the bool for the specific instance is to be changed?
What does the script look like? Are you using statics? Player should have 1 reference to the weapon. ie: Player.EquippedWeapon, Accessing this reference will ignore the extra instances in the scene.
You need to post some code. It is not possible to help you without speculation otherwise. $$anonymous$$y first instinct though is that you are using a static property, when you should not be.
Answer by starikcetin · Oct 26, 2015 at 05:34 PM
I imagine you use GameObject.FindObjectsWithTag
which gives you an array of all objects with that tag. You need to target the gameObject directly (which means "Instance"). You can keep a variable of instantiated gameObject like: GameObject go = Instantialte(...) as GameObject;
If not, then i think your script has static variables and attached to prefab. Static methods/variables/fields etc. belongs to class itself, not the instance of object. So when you do something with a static method/variable/field, then you do that for all the instances of objects that has the class. Try using local fields and methods, then call them from scripts like:
GameObject go = (target gameObject)
go.GetComponent<TypeOfScript>().MethodName();
go.Getcomponent<TypeOfScript>().field = newValue;
Yeah the bool is static variable as it is changed through another script. Looks like I will have to create a work around. Thanks!
Answer by fffMalzbier · Oct 26, 2015 at 05:09 PM
Sounds like you are trying to manage 2 guns from one script instance.
The script that controls the gun should be on the gun and should not use static variables and function for controlling the gun. That way if you have 2 instances of the gun you will have a script instance for every gun object.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity event calling function gets nullreferencexception on bool 0 Answers
Why is my variable always true? 1 Answer