7
\$\begingroup\$

Is there a way to take a script and apply that specific script to an object through code? In pseudocode, what I'm trying to do is essentially as follows:

ObjectOne.MyScript = ObjectTwo.GetComponent<MyScript>();

The closest thing I've found to doing this is AddComponent(), but that only takes either a string or a type and I'd assume it just finds the relavant script and instantiates a clean copy of it. That could work for what I want to do as I could just fill in the relevant information, but that would be tiresome and there should be an easier way to do this.

\$\endgroup\$

1 Answer 1

15
\$\begingroup\$

Yes, the only way is using AddComponent():

var myScript = gameObject.AddComponent<MyScript>();

I don't see how this can be tiresome. There's no way to instantiate a MonoBehaviour so you cannot have multiple instances of your script instantiated by yourself and added them to the game objects on the go - if that's what you thought.


Update

There's really no way to reparent or move a component, so you'll probably have to copy.

However, there's another approach! Instead of having this component in your main Game Object you could instantiate a child Game Object that would just act as a container for your component, and you would move this child to other Game Objects as necessary. Of course the viability of this idea depends on the complexity of the relationship between the main Game Object and the component: if the component uses too many variables of the main Game Object it may be tiresome to reposition it to a child Game Object.

\$\endgroup\$
3
  • \$\begingroup\$ The way it could be tiresome is because I'm specifically trying to take the values (or even just a reference, I'm planning on deleting the first object but as long as there's still a reference to the script it won't be destroyed) of the existing script instead of a blank one. If that's impossible, then fine, I'll have to copy the information into the new blank one. \$\endgroup\$ Commented May 21, 2014 at 10:30
  • \$\begingroup\$ Hm, interesting, I think only now I fully understand your question. I've updated my answer. \$\endgroup\$
    – Roberto
    Commented May 21, 2014 at 21:44
  • \$\begingroup\$ Implementing IClonable probably doesn't work for what I'm doing since there's no way of adding the clone to the second object. As for the child object, that would work in other circumstances, but one of the things I'm trying to do is be able to destroy the original object before adding the script to the second object. In the end, I'm just going to encapsulate all the data in the script within another C# script, so that I can just move that instead of moving the script itself. \$\endgroup\$ Commented May 22, 2014 at 12:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .