- Home /
GameObject is null when assigning to non-monobehaviour public static class
Alright. I've given up. I can't seem to figure this one out. I have a MonoBehaviour script that is attached to an object, and I've got a public static class that isn't monobehaviour. Here is my code: Non monobehaviour script:
using UnityEngine;
using System.Collections;
public static class GameManager
{
//public GameObject Map;
private static GameObject _Map;
private const int _connectorLayer = 8;
public static GameObject Map
{
get
{
return _Map;
}
set
{
Debug.Log(Map);
_Map = Map;
}
}
}
and here is my monobehaviour script that is attached to an object:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Collider))]
public class Map : MonoBehaviour
{
// Use this for initialization
new private Collider collider;
//In world space, this is asigned in Awake.
public float mapHeight;
void Awake()
{
collider = gameObject.GetComponent<Collider>();
GameManager.Map = gameObject;
mapHeight = collider.bounds.extents.y + transform.position.y;
//Debug.Log(collider.bounds.center.x);
}
}
And when I run it, GameManager outputs Null:
Null
UnityEngine.Debug:Log(Object)
GameManager:set_Map(GameObject) (at Assets/Scripts/GameManager.cs:17)
Map:Awake() (at Assets/Scripts/Map.cs:14)
I can't think of anything else this is but a bug in Unity.
Specs:
Unity 5.4.1f1 Personal
Microsoft Visual Studio Tools for Unity 2.3.0.0 enabled
Windows 10 Pro 64-bit build 14393
Included Unity Store Assets:
SteamVR
VRTK
Target Platform: Windows
Architecture: x86_64
Api Compatibility level: .NET 2.0 Subset
Scripting Backend: Mono2x
I've tried running the GameManager.Map = gameObject;
in Awake(), Start() and Update(), and searching for the object and setting it in other MonoBehaviour scripts. I've also tried settings other variables, like strings using the same setup and it works fine! If I try to change GameManager.Map from a type of GameObject to a type of Map, I get the same result, null.
I probably don't fully understand static classes as I've really only used them for singleton style classes. Have you tried making a Singleton style instance and using Game$$anonymous$$anager.Instance.$$anonymous$$ap = gameObject;
Answer by Naphier · Oct 24, 2016 at 08:40 AM
As doublemax says, the setter needs to use "value".
public static GameObject Map
{
get
{
return _Map;
}
set
{
Debug.Log(Map);
_Map = value;
}
}
_Map = Map
... what does Map equal? Nothing. And you'd never be able to set it!
Thanks! I was desperately hoping it would be something silly like that!
Yup, watch those accessors, you gotta be real careful or you'll end up with issues like stack overflows :P
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity3d Dragging object in 3d world 0 Answers