Jump to content

How do I create a global variable that works across all my NPC's?


Recommended Posts

Posted

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?

Posted

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 :D

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.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.