Jump to content

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


aniki432789

Recommended Posts

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.

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

  • Recently Browsing   0 members

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