Add Script on Object using a main script?

Updated on October 8, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on October 2, 2018
I am a total newbie in Unity. I need some help in adding a pre-existing script on a spawn object using a main script. I’ve searched the web but I am confused on their codes specially the articles are quite outdated and Unity changes so quick.
 
My idea is, I have a main script which should spawn new comets via array and I will use a separate script for movement pattern which will be added on each of them upon spawn. Is this even possible?
  • Liked by
Reply
0 on October 2, 2018

Yes it is possible using AddComponent, documentation here.

But I don’t think you need to do that. Can’t you just have the script already on the comet? Why does it need to be added at run-time?

 

  • Liked by
Reply
Cancel
0 on October 2, 2018

Oh thanks ! Well, in various reasons; 1) The comets (plus some spaceships) will respawn/destroy during runtime too. Whether the player hits them or they are out of screen. I figure it will be more organized to add their attack pattern only if they exist in the game. 2) Testing and debugging – if anything comes up, at least I can only deal with a specific script and dont need to mess up with my main. This <addComponent> line can be a comment and voila~ I can check if my main script is bug free or other scripts are conflicting with others.

  • Liked by
Reply
Cancel
0 on October 8, 2018

Why not just make the comets prefabs with the movement script attached?

  • Liked by
Reply
Cancel