- Home /
Instances of Classes
Newbie here. I'm trying to make a shell of an RTS. I have a unit script that I attach to each unit that contains that unit's individual properties (HP, etc), and that is attached to each individual unit. I have another script that is attached to no individual unit that takes care of actions pertaining to all units. However, I would like to make a script to pertain to only some units. It would be a "battalion" script that would group together and work with, say, four units as time. My instinct for making this would be to make a script called battalion and to create a new instance of it, once for every group of four units, and have this script attached to no individual unit. However, I'm seeing a lot about how calling constructors on scripts is something you really should not do in Unity, so I'm confused as to how to proceed. Could someone help out?
As @Loiuzein mentions, you can create classes not derived from $$anonymous$$onoBehaviour and use constructors in a standard C# way, but I usually find it easiest to attach a script like your "battalion" script to an empty game object. I can make it into a prefab and create battalions by calling Instantiate().
Answer by Loius · Feb 02, 2013 at 06:48 AM
There are no 'scripts' in Unity (as opposed to say Python). Anything that doesn't declare a class in UnityScript is automatically declared as a class (using the file's name), and it extends MonoBehaviour. Anything that doesn't declare a class in C# just won't compile.
You can't use a constructor of a an object which extends MonoBehaviour. If you create your own class extending "not MonoBehaviour", you can call the constructor all you want. You have to use AddComponent for Component-type classes because Unity needs to do behind-the-scenes stuff to get everything working for you.
Your answer
Follow this Question
Related Questions
Calling a function across all instances of an object 2 Answers
Build Queue Logic In Turn-based Strategy 1 Answer
Cannot get variable from another class. Error: NullReferenceException 2 Answers
How to select a class instance from the inspector? 1 Answer
How to access an instance of a class when the class isn't known 2 Answers