How to declare a struct in C#

Hello everyone.

I’m trying to create a simple struct to hold data (not methods, just some properties), and I want it to be accessible from all my other scripts, like if it was just another class from the unity engine (Vector3 for example).

So I mostly know the differences between struct and class, and I want it to be a struct, not a class.

So how should I do it? As far as I know, unity doesn’t let me attach a script with just a struct declaration, scripts are classes which inherit from monobehaviour, and structs cannot be inherited from classes (correct me if i’m wrong) so how do I declare the struct? Should I declare it inside of a public class, and then attach that script onto a gameObject? Or is there a better way to do this?

You can’t just stick a struct onto a gameobject, since it requires functionality that inherits from ‘Component’ in order for that to work. however, you can just declare structs in your files, the normal way:

public struct MyStruct {
    // variables
}

Keep in mind that structs will not be serialized by Unity, and as such cannot be used to save data between sessions. If all you are using them for is data transfer (messengers), this is fine- but if you want them to be serialized and visible from the inspector, you will need to declare them as classes, and use the ‘System.Serializable’ attribute.