- Home /
Add all scripts to gameObject from var
Hey All,
Is it possible to store all scripts from one object into a variable and then add those scripts to another object?
For example, something like:
var scriptList : MonoBehaviour [] = GetComponents(MonoBehaviour);
var otherObject = Instantiate(monster);
otherObject.AddComponent(MonoBehaviour) = scriptList;
I've been trying versions around this, but nothing has worked so far. I do not want to name a specific script. I just want to get whatever script is attached.
Answer by toddisarockstar · May 20, 2017 at 01:47 AM
one way or another you would need to differentiate your own components from unity's. the scripts you write are components just like the others. So I would make a list of scripts to look for so you are not coping over rigidbody and animators and stuff. Cause they are scripts too!
var tocopy:String = "MoveScript AIscript WhateverScript blah blah";
var comps:Component[];
var i :int;
// get a list all of compents attached to this object
comps=GetComponents(typeof(Component));
i = comps.Length;
while (i>0) {
i--;
print(comps [i].GetType ().ToString ());
// see if it is in our string before adding to the new object
if (tocopy.Contains (comps [i].GetType ().ToString ())) {
otherObject.AddComponent (comps [i].GetType ().ToString ());
}
}
alternatively you could Look for the term "unityengine" in the name of the component and filter it that way but i would reccomend the list approach to give you a bit more controll!!!!!!
Hey, you are a rockstar. :P Thanks for the answer! This explains a lot. Although I when another route with what I was actually doing (since my question had been waiting for moderation the last few days), I'll be sure to simplify other code that I was working on with this technique. So, thanks again for taking the time to answer! :)
Your answer
