jacksondunstan / UnityNativeScripting

Unity Scripting in C++

Home Page:https://jacksondunstan.com/articles/3938

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Compare Strings

dajevtic opened this issue · comments

I really enjoy your project a lot. Spent the last few days using the generator and porting a lot of functions to C++: Vector3, Quaternions, GameObjects, etc.
I am stuck with a fairly simple task though... Though I manage to expose my GameObjects, their names, tags, etc. I am unable to do the most simple task, which is to check if a GameObject's Tag (String) equals another String's value (the Tag of another GameObject)...
How do I use a simple check in C++ whether one GameObject's Name or Tag equals another one's?

Hi @dajevtic, I'm glad you're enjoying the project!

Unfortunately, string comparison is not currently directly supported. This is because strings are special-cased in the project so you can't simply expose their == operator in the bindings like you would with other types. However, you could create your own function to compare strings and expose it. Something like this:

namespace MyProject
{
    public static class StringUtils
    {
        public static bool IsEqual(string a, string b)
        {
            return a == b;
        }
    }
}

Then expose it as usual in the JSON bindings config and call it from C++:

System::String aName = aGameObj.GetName();
System::String bName = bGameObj.GetName();
bool same = MyProject::StringUtils::IsEqual(aName, bName);

However, in the specific case of comparing GameObjects' tags, I'd recommend exposing and using CompareTag as it won't create any string instances which are likely to very shortly become garbage for the GC to collect. Unfortunately, there is no CompareName so you'll need a workaround like the one above.