Unity Tip – Using Variables in C# Attributes

Hello,

After watching this talk at Unite 2014 about editor scripting and specifically using Menu Items to open scenes in your project:

I thought I would give it a go myself…

Attributes Example 1 - Scenes Menu Item in Unity
Attributes Example 1 – Scenes Menu Item in Unity

It works beautifully!

However this could lead to a few problems if you have many scenes in your project…

The Problem:

If you use the same menu names for mulitple entries, then it can start to get a bit monotonous!

Attributes Example 2
Attributes Example 2 – – Potential Monotonous Coding!

So I thought I would try to use a variable to save me copying and pasting the same string (this could lead to some potential errors when debugging), but that was a no go:

Attributes Example 3 - Non-static Reference Errors
Attributes Example 3 – Non-static Reference Errors

This means that the reference needs to be static (constant) and so if we want to use a variable, it can’t be variable.

The Solution:

Make the variable constant! (using the const reference):

Hopefully this post has been helpful to you 🙂

Any suggestions or comments please feel free to add to get in contact 🙂 .

Leave a Reply

Your email address will not be published. Required fields are marked *