【问题标题】:Disabling every GameObject except one禁用除一个以外的所有游戏对象
【发布时间】:2022-11-15 16:43:31
【问题描述】:

我正在尝试制作一本书,如果用户按页面 SetActive(false)GameObject 除了选定的 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 );
}

我试过continue方法。

【问题讨论】:

  • 当你运行这段代码时会发生什么?
  • 所有页面都设置为不活动
  • 只需将两个 int 变量设为 CurrentPage NextPage。和他们一起玩,因为你只有一个页面是活动的,我们选择一个新页面,你禁用它并启用新页面。

标签: c# unity3d


【解决方案1】:

解决此问题的更好方法是跟踪最后一个活动页面并在选择任何其他页面时将其停用。那会快很多。

您还可以编写一个函数,将所选页面作为参数,停用当前页面,将当前页面分配给所选页面参数并激活所选页面。是这样的:

public GameObject[] bookPages;
int currentPage;

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

    currangePage = pageIndex;

    bookPages[currangePage].SetActive(true);
}

【讨论】:

  • 如果我有 6 页,那么我只希望第 4 页处于活动状态,而其余页面则处于非活动状态怎么办?
【解决方案2】:

我在您的原始代码中看到拼写错误。你有currentPage 而不是currentPage。这肯定会导致 Unity 停止执行该方法。您会在控制台日志中看到一条红色的异常消息。

但是为了使代码更简单,您可以这样处理它:

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 ( );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    相关资源
    最近更新 更多