Using same class name like builtin class?

I want to have a class named Tree, for my trees. It is inside my projects namespace.

Unity says:

Script 'Tree' has the same name as built-in Unity component.
AddComponent and GetComponent will not work with this script.

Does it really not work?
I really can’t think of a better class name. TreeBehaviour might be confusing when having BehaviourTrees. Any ideas?

the simplest thing you can do is to create your classes using a specific naming convention that is familiar to you.

so instead of calling the class Tree call it TZ_Tree (using your username as example)

there are some advanced c# topics like namespaces if you have time for that

I have my tree class in my own namespace and Unity gave me the message.

namespace MyNameSpace
{
    public class Tree : Vegetation
    {

Called from inside a class in MyNameSpace:

        public void GetTree()
        {
            var tree = GetComponent<Tree>();
            print(tree);

            tree = GetComponent<MyNameSpace.Tree>();
            print(tree);
        }

Both print MyNameSpace.Tree. But I guess to avoid confusion I rename it to TreeComponent or something.
I was just somewhat confused by the message and thought it wouldn’t work despite having a different namespace.

Yes, because it is finding your Tree first in the name resolution search order because it is in your assembly.

If you want the one in UnityEngine, say so with UnityEngine.Tree

Thanks, good to know.

One thing to add: even though you do need to change the name of the class to something else, you can still at least make it appear as just “Tree” in the Inspector using the AddComponentMenu attribute :slightly_smiling_face:

[AddComponentMenu("Vegetation/Tree")]
class TreeComponent : Vegetation {  }
2 Likes