Home > Mobile >  Disabling every GameObject except one
Disabling every GameObject except one

Time:11-15

I'm trying to make a book where if the user press the pages it SetActive(false) every GameObject except the selected GameObject.

public GameObject[] bookPages;
int currentPage;
    
public void whatPage ( )
{
    int pages = 0;
    while ( pages < bookPages.Length )
    {
        if ( pages == currentPage )
        {
            Debug.Log ( "CURRENT PAGE"   currentPage );
            bookPages [ currentPage ].SetActive ( true );
            pages  ;
            continue;
        }
        bookPages [ pages ].SetActive ( false );
        Debug.Log ( pages );
        pages  ;
    }
}

public void pageFlu ( )
{
    currentPage = 1;
    whatPage ( );
    bookPages [ currentPage ].SetActive ( true );
}

I have tried the continue method.

CodePudding user response:

A better approach to this problem would be keeping track of the last active page and deactivating it when any other page is being selected. That would be a lot faster.

You could also write a function that takes the selected page as parameter, deactivates current page, assigns current page to the selected page parameter and activates the selected page. Something like this:

public GameObject[] bookPages;
int currentPage;

public void DeactivateAllPages()
{
    foreach (GameObject page in bookPages)
    {
        page.SetActive(false);
    }
}

public void SelectPage(int pageIndex)
{
    bookPages[currangePage].SetActive(false);

    currangePage = pageIndex;

    bookPages[currangePage].SetActive(true);
}

CodePudding user response:

I see a spelling mistake in your original code. You had currentPage instead of currentPage. That would certainly cause Unity to stop the execution of that method. You would see a red Exception message in your console log.

But to make the code simpler, you could approach it something like this:

public GameObject[] bookPages;
int currentPage;
    
public void whatPage ( )
{
    for ( int i = 0; i < bookPages.Length; i   )
        // also handles a bad 'currentPage' value by setting all to inactive.
        bookPages [ i ].SetActive ( i == currentPage ); 
}

public void pageFlu ( )
{
    currentPage = 1;
    whatPage ( );
}
  • Related