Posted August 3, 20214 yr I need to create a global variable that I can use with all my NPC's. For example, I would have a global variable named 'Seen'. If an NPC see's the player and Seen equals false then it would attack and Seen would be changed to true. If Seen equals true the NPC would ignore the player. How and where would I create this variable, and how would I reference it?
August 9, 20214 yr This is a classic design pattern, you have to implement Singleton Pattern. Wikipedia: The singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The pattern implementation is easy to found but here is a quikly example: Create a new class with all the attributes you need (boolean seen) and the Class as property. Make your constructor as PRIVATE and create an static method to get the instance. public final class Singleton { private static Singleton instance; public boolean seen = false; // Default value private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } Where you need use the instance you always will use "getInstance" method: Singleton myInstance = Singleton.getInstance(); It doesn't matter where you call the "getInstance" method from. For access to the value or modify it, simply like this: myInstance.seen = true; The idea is that you will only create instance once, the second time when you call getInstance method you will get the same created instance and not a new one. I hope this help you
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.