Jump to content

Checking to see if an object exists without crashing if it doesnt


Recommended Posts

Posted

Hello, just trying to learn more about the api.

As of now I'm working on a simple cannon script but I don't know the best way to go about fixing the cannon incase it breaks. The cannon goes from "Dwarf multicannon" to "Broken multicannon" and I don't know how to interact with the Broken multicannon optimally.

I declare the working cannon as cannon = getObjects().closest("Dwarf multicannon")

But this only works assuming the working cannon does actually exist. If it doesn't exist, the script crashes.

So, for example, if I'm trying to check if the Broken multicannon exists, I can't use getObjects().closest("Broken multicannon") in anyway else bad stuff goes down.

 

So, my question is, is there a safer way of checking if something exists without everything breaking if it does not?

Thank you for your time.

Posted

One way, using null checking:

RS2Object object = getObjects.closest("Dwarf multicannon");
if(object != null) {
//do things
}


Another way, using streams:
 

       Optional<RS2Object> object = objects.getAll().stream().filter(i -> i.getName().equals("Dwarf multicannon")).findAny();
       if(object.isPresent()) {
           RS2Object cannon = object.get();
           //do stuff
       }

 

  • Like 2

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...