x


Adding components to objects that have the same tag

I whant to be able to stete several components to a group of objects with the same tag. I also whant to be able to add a object to the transform in the script automaticly. Can i do this? And if you can how?

more ▼

asked Feb 26 '12 at 10:51 PM

finndaly gravatar image

finndaly
1 2 3 5

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

1 answer: sort voted first

I didn't understand exactly what you wanna do, but you can get all objects with a given tag using FindGameObjectsWithTag(tag), then attach whatever you want to them - like this (code attached to any object in scene):

var prefab: Transform;

function Start(){
  var gOs = GameObject.FindGameObjectsWithTag("MyTag");
  for (var gObj in gOs){
    gObj.AddComponent(Rigidbody); // add a component like Rigidbody, for instance...
    gObj.AddComponent(MouseLook); // or add a script like MouseLook.cs
    // if you want to instantiate some object and child it to gObj:
    var child = Instantiate(prefab, gObj.transform.position, gObj.transform.rotation);
    child.parent = gObj.transform; // make gObj the child's parent
  }
}

NOTE: Avoid using the GameObject.FindXxxx functions in Update - they aren't fast, and may slow down your game.

more ▼

answered Feb 27 '12 at 12:00 AM

aldonaletto gravatar image

aldonaletto
41.3k 16 42 195

thats perfict but i whant to add code to each object with the tag and using

var target : Transform;

to set the target at the same time so that the script gets added and the target is added to the code.

Feb 27 '12 at 10:39 PM finndaly

You could find the target in this script and assign it to the target variable in each new script added:

function Start(){
  // find the target once in the script above:
  var theTarget = GameObject.FindWithTag("Target").transform;
  var gOs = GameObject.FindGameObjectsWithTag("MyTag");
  for (var gObj in gOs){
    var script = gObj.AddComponent(MyScript) as MyScript;
    script.target = theTarget; // define the object target
  }
}

Another alternative is to let each script find the target at Start (script you want to add to the objects):

function Start(){
  // find the target at Start:
  target = GameObject.FindWithTag("Target");
  ...
Feb 28 '12 at 12:46 AM aldonaletto
(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:

x1276
x137
x20

asked: Feb 26 '12 at 10:51 PM

Seen: 465 times

Last Updated: Feb 28 '12 at 12:46 AM