x


How to get script components in multiple gameobjects C#

I want to change a variable in a script which is in multiple gameobjects, I tried to use public GameObject enemy; and in the update I had enemy = GameObject.FindGameObjectsWithTag("Enemy"); but that won't work, how do I select every gameobject with tag "Enemy" and change a variable in all of their scripts?

more ▼

asked Sep 26 '10 at 04:34 AM

MonkeyAssassin8 gravatar image

MonkeyAssassin8
271 35 38 43

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

You're on the right track.

You should probably do it less often than in every Update(), but FindGameObjectsWithTag will work. You then need to get the component (script) that the variable is in, using GetComponent, and then you can set it.

  1. Gather array of all GameObjects tagged as "Enemy"
  2. Use a forloop to iterate through all those gameObjects, and use GetComponent (or use Messages) to access the variable inside that script.

You just need to make sure that the variable you're declaring on those objects is publicly accessible (i.e. not in a function, and declared as public)

more ▼

answered Sep 26 '10 at 07:24 AM

Marowi gravatar image

Marowi
4.9k 4 14 53

(comments are locked)
10|3000 characters needed characters left

Instead of using public use static; that should keep your variable the same value in all instances of the script.

more ▼

answered Sep 26 '10 at 06:58 AM

PeterDC gravatar image

PeterDC
277 2 4 14

That won't work. Using static will make a single, game-wide variable. He's asking to change a variable in multiple GameObjects. Unless he actually needs them all to be the same value, he'll need a public variable in each.

Sep 26 '10 at 07:26 AM Marowi

Oh, sorry; guess I interpreted it incorrectly.

Sep 26 '10 at 07:34 AM PeterDC

that was actually what I wanted... I wanted to change the health of all of the enemies. thanks for the help.

Sep 26 '10 at 08:39 AM MonkeyAssassin8
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3330
x798
x323
x292

asked: Sep 26 '10 at 04:34 AM

Seen: 1829 times

Last Updated: Sep 26 '10 at 04:34 AM