简体   繁体   中英

Access to the variable between multiple scripts for loose coupling in Unity3D

For instance, assume we have a health variable in one script and want to access to this variable in UI script for showing health and on the other hand change pitch of sound according to amount of health. I know some ways to access this variable but they highly dependent scripts to each other. Like GetComponent, Singelton or even C# event. I want to know is there any patterns to decrease these dependencies ? (Also efficient and performant)

Edit: This event system is in my mind but I think It has some dependencies which they can be removed but I don't know how and also I'm not sure about it and its performance.

public class Player {
    public class HealthEventArgs : EventArgs {
        public int currentHealth;
        public HealthChangedEventArgs(int currentHealth) {
            this.currentHealth = currentHealth;
        }
    }

    public static event EventHandler<HealthEventArgs> HealthEvent;

    public void NotifyHealthChanged(int health) {
        if(HealthEvent != null) {
            HealthEvent.Invoke(this, new HealthEventArgs(health));
        }
    }
}

public class OtherClass {
    public void SubscribeToPlayerHealthEvent() {
        Player.HealthEvent += Foo;
    }

    public void UnsubscribeFromPlayerHealthEvent() {
        Player.HealthEvent -= Foo;
    }

    public void Foo(object o, HealthEventArgs e) {
        //Do something with e.currentHealth
    }
}

after @ julxzs and i were talking...

did a little checking on best practices... i found this

link

so it turns out singleton is the way to go, check out the page, lots of good info! thx @julxzs

Take a look at dependency injection technique. I can advice to start with Zenject .

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