C++ struct to C#

Wondering if someone could help me. Im a C++ programmer and want do the following in C# on a scriptable object. Any reasons why I shouldn’t implement a struct inside a scriptable object. Im new to Unity and C#

    struct Data{
        int index;
        bool hit;
        char names[];
    };
    std::vector<Data> data;
    data.reserve( num );

I’m not entirely sure what the code is meant to acocmplish, but declaring and using structs in C# is not too different from C++. The biggest syntax difference I see is that [ ] would go after char (and, stylistically, you’d almost certainly want to use string instead). C# has List for resizable arrays, rather than vector, and you should check out C# documentation to learn how that works.

If that’s not sufficient help, then I think I’d need more context as to what you’re trying to accomplish.

1 Like

One thing to note about Unity is that structs do not get serialized and displayed in the inspector. So your “data” list will not be editable in your Scriptable Object instances.

This is one equivalent that is editable in the inspector:

using UnityEngine;
using System;
using System.Collections.Generic;

public class myclass : ScriptableObject {
    [Serializable]
    public class Data {
        public int index;
        public bool hit;
        public string[] names;
    }

    public List<Data> data;
}

You can make things private/protected and use the [SerializeField] attribute to tailor the public interface.

Perfect thanks guys

Unity changed this.

You can now mark structs as serializable.

Oh, wonderful. Nevermind that part then.

So I can use a struct instead of a class ?

Yes:

[Serializable]
public struct Data{
   public int index;
   public bool hit;
   public char[] names;
};
List<Data> data = new List<Data>(num);

Though I guess I should add that if you’re displaying that list in the inspector, then creating it with a starting buffer size is pretty pointless; it’s going to be recreated every time you change it in the inspector.

Cool thanks for the reply , this will purely be for data management. Serializable is just a bonus , ill see how it all turn out