- Home /
How to get all scripts attached to a gameojbect?
How to get all the scripts attached to a gameobject and add them into antoher gameobject with the variable values in those scripts untouched?
Answer by Ashkan_gc · May 05, 2011 at 02:39 AM
you can get all scripts attached to a gameObject because the type of all of the is MonoBehaviour but then you can not change their values cause they should be casted to their type for their values to be accessible. i mean if you have a script called Gun, it's a child of MonoBehaviour so if you say
MonoBehaviour[] scripts = GetComponent<MonoBehaviour>();
then scripts will contain all scripts attached the gameObject with the script (including Gun script). but then you can use a monobehaviour's properties and functions on them and for example Gun's ammo variable can not be seen.
so there is not a general way to get all of them but you can get them all by getcomponent and then create a new object of their type and copy them to the new object (with =) and then add the new object of type (say Gun) to the other object with AddComponent but it's not a good way for coding it.
tell me what do you want to do in highlevel to recommend you a better way.
First of al, thank you for answering my question. It's used to transform my player to a new job class (like rookie ->warrior). The best way is to just change model inside the same player's gameobject. But not sure how it can be done.
So what I am doing now, is to have warrior prefab with different model. When transform starts, I instantiate warrior prefab in same location and destroy my rookie. And So the values of variables in the scripts also able to transfer over.
Your answer
Follow this Question
Related Questions
Generic way to get properties on Component? 3 Answers
Adding a script component through scripting 1 Answer
enable/disable specific components 3 Answers
Get Component on Instantiated Object 1 Answer