简体   繁体   中英

How do I access higher level variables/objects in a child object?

Something I haven't ever figured out how to do in C# is the following:

Say I have two classes: Game.cs, and Player.cs.

I find that anything that belongs to Game.cs must be passed on through the arguments of any function that belongs to Player.cs. For example, if I had a sound effect loaded in Game, and Player was a child of Game, and Player has a function "PlaySoundEffect()", the only way that Player could access that sound is if I pass it through the arguments: "PlaySoundEffect(SoundEffect sound)"

What I want to know is this:

  1. How can I access the object(s) without including them as an argument?
  2. Why can't I access them like so: "Game.sound", even though sound is in Game?

sound is a property of any specific instance of Game .

You can only get it from a specific instance.

Instead, you can add a Game instance as a property of Player , so that each player has a reference to its game.

You can't access them because they aren't static .

But,

You could wrap them, and pass them to the player. Something like this:

class GameSoundManager {
    public SoundEffect PlayerDie { get; set; }
}

class Game {
    private GameSoundManager _soundManager;
    private Player _player;

    public Game() {
        _soundManager = new GameSoundManager() {
            PlayerDie = // load the sound
        };

        _player = new Player(_soundManager);
    }
}

class Player {
    private GameSoundManager _soundManager;

    public Player(GameSoundManager soundManager) {
        _soundManager = soundManager;
    }

    // use _soundManager.PlayerDie anywhere in your player class.
}

Just make any global variables in your Game class static - meaning, they aren't part of the Game instance, and instead are globally accessible.

EG, in Game.cs
SoundEffect sound;
becomes
static SoundEffect sound;

Now your player class can just do
Game.sound.Play();
or whatever it needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM