- Home /
Poster found answer
Building an identify script
I am trying to build a game that will have an unknown number of objects. These object won't do anything, they will just sit in the scene. What I am trying to do is build a system that will allow me to identify and instantiate all objects that meet certain criteria. What I am having trouble with is building a script for the individual items. I want to use the same script for each item, but have separate fields available to the user based on earlier decisions that they make about the object. For example, if the user sets a type variable in the script to sphere a new option will appear asking if the item can roll. Is there a way to do this or should I just have separate classes for each item?
Answer by JVene · Aug 02, 2018 at 08:47 PM
Read about the component system in Unity. You'll discover that a sphere renderer (and, for the roll question, a sphere collider and rigidbody) are components you can add at runtime. So it is with a rectangle or a mesh. You'll have to understand how these components are created and added to an otherwise empty gameobject (which can also instantiate).
If you experiment "manually" in the editor, add a sphere and then a rectangle, then examine the objects in the inspector. You'll see they are the same basic empty gameobject, with sphere and rectangle renderers, materials (defaults at first), and possibly colliders, all added as components.
That's the model you follow. You'll need to read up on Unity scripting, how to obtain materials, how to create physics materials, how to load resources from the library and a host of other learning on these points, but what you've outlined is not only possible, it is exactly in line with the way Unity's component system is design.
You'll probably want to study C# more generally. Unity students tend to think in terms of scripts, but scripts are just text files. The key focus is the class, AKA an object (when instantiated). You'll want to study abstract methods and abstract classes, because I sense they are directly applicable to what your description leads to.
I don't want to actually add colliders or rigidbodys via code. I was simply using that as a example. What I want to be able to do is add custom fields to an object.
Simply add member variables the script created when you add a script to the objects in question.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Creating class instances 1 Answer
Accessing class variables from a definition 1 Answer
Get list of all "Action" classes 1 Answer