- Home /
Instantiating an Object in a Class?
What I want to do is use classes for different types of trees. Keep things organized and logically together.
So I setup my base tree class and then extend it for a specific type of tree:
class Trees {
var Obj : GameObject = new GameObject("Tree");
var filter : MeshFilter = Obj.AddComponent(MeshFilter);
var renderer : MeshRenderer = Obj.AddComponent(MeshRenderer);
}
class Sycamore extends Trees {
function Sycamore() {
filter.mesh = Resources.Load("Art/Meshes/Environment/Trees/Sycamore", Mesh);
}
}
Next I want to create a sycamore at a specific location (and later multiple locations using an array for the trees) and I'm not having any luck trying to instantiate it. Is there another, better way - or if instantiating is the way to go can someone provide a same line to do so?
Thanks!
Answer by Waz · Jun 28, 2011 at 11:05 PM
You're fighting against Unity's component model.
Instead, make Tree a standalone script, not wrapped in class { ... }
. That will give you a Tree Component (this is just a shorthand for extending MonoBehaviour, but ignore that for now). Then you can drag that component into your Sycamore prefab.
You probably don't even need subclasses, since a Sycamore does not behave differently to any other tree. In all fields of computing, building a deep hierarchy is usually a mistake, a trap set by professors who use Shapes, Trees, and Cars as example hierarchies.
Yeah I was thinking about doing that. Eventually each tree will have it's own properties, but I can include those in the base tree script and modify per tree species.
Thanks!
Correct. You might even break out some behaviour as a different reusable script, say, Bendy, that deforms a mesh and has a blowInTheWind
property. You'll reuse that on your Skyscraper prefab.
Your answer
![](https://koobas.hobune.stream/wayback/20220612124817im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can I call a class's method which inherit monobehaviour by a normal class? 0 Answers
Using a top level variable in a class 0 Answers
Instantiating a class 1 Answer
How to create multiple Characters? 2 Answers
Unity script system 2 Answers