Having problems passing structure back from a method

I’ve created the following simplified scenario to illustrate my problem.

I created a new project. I created 2 empty gameobjects and made one the child of the other. I called them MyParentGameObject and MyChildGameObject.

I created a script called MyChild and attached it to MyChildGameObject. I created a script called MyParent and attached it to MyParentGameObject.

Here are the contents of MyChild script :-

using UnityEngine;

using System.Collections;


public class MyChild : MonoBehaviour {

    public struct MyStructureInChild
    {
        public int ReturnedInteger;
        public string ReturnedStringA;
        public bool ReturnedBool;
        public string ReturnedStringB;
    }
    public MyStructureInChild myStructureInChild;

    public MyStructureInChild DoSomething(string PassedIn)
    {
        myStructureInChild.ReturnedInteger = 101;
        myStructureInChild.ReturnedStringA = "Hello";
        myStructureInChild.ReturnedBool = true;
        myStructureInChild.ReturnedStringB = "World";
        return myStructureInChild; 
    }

}

Here are the contents of MyParent script : -

using UnityEngine;
using System.Collections;

public class MyParent : MonoBehaviour {

    public struct MyStructureInParent
    {
        public int ReturnedInteger;
        public string ReturnedStringA;
        public bool ReturnedBool;
        public string ReturnedStringB;
    }
    public MyStructureInParent myStructureInParent;

    void Awake()
    {
        myStructureInParent = transform.Find("MyChildGameObject").GetComponent<MyChild>().DoSomething("Hello");
    }
}

The problem is that I get the following error from Line 17 of MyChild "Cannot implicitly convert type ‘MyChild.MyStructureInChild’ to ‘MyParent.MyStructureInParent’ ".

Since the structures are identical, I would expect there to be no problem.

If I’m not mistaken, even though two structs appear identical, your compiler doesn’t see it that way. For compiler it is the same as trying to convert class A into B that are not the same (don’t share same parent class).

If you know your structs will have same values, you could define a single global struct:

public struct MyGlobalStruct
{
     public int ReturnedInteger;
     public string ReturnedStringA;
     public bool ReturnedBool;
     public string ReturnedStringB;
 }

public class MyClass : MonoBehaviour
{
    // rest of class...
}

Hope it helps. If I’m mistaken, please correct me!

2 Likes

Thanks for that. I’m going down the path of a global struct, I was just wondering why this problem occurs.