iibrahimbakr
iibrahimbakr

Reputation: 1134

Call function from render method one time (libGDX)

In this test code:

 @Override
    public void render() {
        test();
    }

    private void test() {
    }

How can I call test(); one time (NOT loop) ?

Upvotes: 2

Views: 818

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13581

One way is simple flag. Just create a boolean that will tell you if test() was called

    boolean isTestCalled = false;

    private void test()
    {
        System.out.println("test!");
    }

    @Override
    public void render(float delta) 
    {
        if( !isTestCalled )
        {
            isTestCalled = true;
            test();
        }

        ...

you can change boolean to int and increase it every time you will call test() to limit test call count. I don't very like flags - it generates spaghetti code.


If it would be C++ the second option would be using static variable inside test function and just tell it how many times it should be called - but hey this is Java :). Statics are only for classes but you still can simulate it:

    //even inside your class
    static class Counter
    {
        public static int count = 0;
    }

    private void test(int limit)
    {
        if( ++Counter.count <= limit ) //here you can add something like ...&& limit > 0 to have and option to infinite calls when calling test(-1) for example
        {   
            System.out.println("test!");
        }
    }

    @Override
    public void render(float delta) 
    {
        test(2);

        ...

And last but not least - in case you want to call test() exactly on a start of render - just move it to the show() function. But I guess it is not what you want to do when you are creating a question like this.

Upvotes: 4

Related Questions