用于项目选择的C#Unity脚本

时间:2018-10-22 12:01:25

标签: c# unity3d gameobject

我目前有一个脚本,可将2个预制件实例化为GameObjects。这些脚本已将game-object设置为false的脚本附加到他们,然后将其添加到我的inventory数组中。这是另一个脚本,但是我的问题是尚未选择的另一个游戏对象仍然存在。应该是您可以选择2。一旦您选择一个,另一个就会消失。我不知道该怎么做,任何人都可以帮忙。

public int moralityCounter=0;
public bool Inventory;

public void Store()
{
    if (gameObject.CompareTag("Good"))
    {
        moralityCounter++;
        Debug.Log(moralityCounter);
        gameObject.SetActive(false);
    }
    if (gameObject.CompareTag("Bad"))
    {
        moralityCounter--;
        Debug.Log(moralityCounter);
        gameObject.SetActive(false);
    }

}

1 个答案:

答案 0 :(得分:1)

如果只有单个good和单个bad标记的对象,则可以将标记为好和坏的所有内容都设置为不活动。

private void DeactivateAllGoodBads() 
{
    // Deactivate all goods
    GameObject[] goodObjects = GameObject.FindGameObjectsWithTag("Good");
    foreach (GameObject goodObject in goodObjects)
    {
        goodObject.SetActive(false);
    }

    // Deactivate all bads
    GameObject[] badObjects = GameObject.FindGameObjectsWithTag("Bad");
    foreach (GameObject badObject in badObjects)
    {
        badObject.SetActive(false);
    }
}

public void Store()
{
    bool isGood = gameObject.CompareTag("Good");
    bool isBad = gameObject.CompareTag("Bad");
    if (isGood)
    {
        moralityCounter++;
        Debug.Log(moralityCounter);
    }

    if (isBad)
    {
        moralityCounter--;
        Debug.Log(moralityCounter);
    }

    if (isGood || isBad)
    {
        DeactivateAllGoodBads();
    }  
}

如果有多个对象,则可以执行一些操作,例如仅禁用比“存储对象”更远而不是某个距离的对象。

private void DeactivateCloseGoodBads(Vector3 position, float maxDistance)
{
    // Deactivate close goods
    GameObject[] goodObjects = GameObject.FindGameObjectsWithTag("Good");
    foreach (GameObject goodObject in goodObjects)
    {
        // Check distance of found good
        if (Vector3.Distance(position, goodObject.transform.position) <= maxDistance) {
            goodObject.SetActive(false);
        }
    }

    // Deactivate close bads
    GameObject[] badObjects = GameObject.FindGameObjectsWithTag("Bad");
    foreach (GameObject badObject in badObjects)
    {
        // Check distance of found bad
        if (Vector3.Distance(position, badObject.transform.position) <= maxDistance) {
            badObject.SetActive(false);
        }
    }
}

public void Store()
{
    bool isGood = gameObject.CompareTag("Good");
    bool isBad = gameObject.CompareTag("Bad");
    if (isGood)
    {
        moralityCounter++;
        Debug.Log(moralityCounter);
    }

    if (isBad)
    {
        moralityCounter--;
        Debug.Log(moralityCounter);
    }

    if (isGood || isBad) 
    {
        DeactivateCloseGoodBads(gameObject.transform.position, 10f);
    }

}