Quantcast
Channel: Answers for "Creating a pointer variable to a GameObject inside a class that does not extend MonoBehavior? [C#]"
Viewing all articles
Browse latest Browse all 4

Answer by Bunny83

$
0
0
I think you have to start to use the right terms as in C# there are actual [pointers][1] (only available in an unsafe context) and [references][2]. In C# most the time you will work with references and not pointers. Depending on your target platform unsafe code isn't supported at all. Even if it's possible you have to add the "-unsafe" compiler switch so unity even compiles such code. You have to be more precise when you say you want to "store" a reference to one or more GameObjects. Do you mean store at runtime or do you mean store the references as edit time and have those references serialized so you can use them at runtime? The first case shouldn't make any problems. If you have a custom class (not inherited from MonoBehaviour) you can of course have GameObject fields (variables) in your class and you can assign a GameObject reference to this variable. The second case is more complicated since Unity does only serialize classes derived from UnityEngine.Object. Things are always stored as "assets" at edit time. There are different kind of assets types. A GameObject with a MonoBehaviour derived class might be stored as prefab or along with a scene asset. To be able to store a standalone asset that isn't a GameObject you have to derive your class from ScriptableObject. However you have to write an editor script to actually create and store such an instance. Unity also provides a ways to use custom classes like structs by adding the System.Serializable attribute to your custom class. This class can't be serialized on it's own, but it can be serialized along with a MonoBehaviour or a ScriptableObject. Example: [System.Serializable] public class MyCustomClass { public string someStringData; public GameObject aGameObjectReference; } public class MyComponent : MonoBehaviour { public MyCustomClass obj1; public MyCustomClass obj2; } "MyCustomClass" is treated like a struct when Unity serializes the MonoBehaviour. So it's values are simply stored along with the MonoBehaviour. If you want a more detailed answer, you should describe your problem more in detail, maybe with a code snippet. [1]: http://msdn.microsoft.com/en-us/library/y31yhkeb%28v=vs.80%29.aspx [2]: http://msdn.microsoft.com/en-us/library/490f96s2%28v=vs.80%29.aspx

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images