- Home /
Having trouble with static references.
So I have a Local Players script which keeps track of four Player singletons. Each player singleton refers to a Camera instance, which is supposed to be limited to 1 per player. But every time I refer to the camera instance, it keeps spawning new ones, although the reference remains on the real one.
Here are the important bits. What could I be doing wrong?
public class Players : MonoBehaviour {
private static Player _player1;
public static Player p1 {
get {
if(_player1 == null) {
_player1 = new Player(1);
}
return _player1;
}
}
}
public class Player {
//Private Variables
private bool _active;
private Camera _camera;
//Class Variables
public bool active {
get {
if(_active == true) { camera.enabled = true; }
else { camera.enabled = false; }
return _active;
}
set {
if(value == true) { camera.enabled = true; }
else { camera.enabled = false; }
_active = value;
}
}
public Camera camera {
get {
if(_camera == null) {
_camera = (new GameObject().AddComponent("Camera")).camera;
_camera.gameObject.name = "Player Camera";
Object.DontDestroyOnLoad(_camera);
}
return _camera;
}
set {
if(_camera != null) {
Object.Destroy(_camera);
}
_camera = value;
}
}
}
public class Motor : MonoBehaviour {
Player _player;
void Awake() {
_character = GetComponent(typeof(Character)) as Character;
_player = _character.player;
if(_player != null) {
_cam = _player.camera; //RIGHT HERE. This little guy keeps making my Player script spawn new cameras.
}
rigidbody.freezeRotation = true;
characterCollider = (CapsuleCollider)GetComponent(typeof(CapsuleCollider));
}
}
Answer by TowerOfBricks · Jun 27, 2011 at 07:18 PM
I'm not sure if this is the correct answer since you should be getting a NullReferenceException, but anyway. When you are creating the _camera gameObject, you are adding a PlayerCamera component (whatever that is), but you are not adding a Camera component (which should cause the call to .camera to return null). But perhaps your PlayerCamera script has a RequireComponent attribute and that adds it. Otherwise I cannot see anything wrong with the code.
And also, your SerializeField attributes won't do anything since your class (Player) isn't serializable, mark it with [Serializable].
Ah yeah, that script requires a camera. $$anonymous$$y SerializeField stuff was for debugging and such. I'll edit it out.
Very odd. For some reason, it just keeps adding a camera every time I make a new character with that Character$$anonymous$$otor script. That line "_cam = _player.camera;" seems to be the culprit. It references a player, which seems to work fine on its own, but as soon as I reference the camera through its getter, it creates a new one, yet still references the original.