首页 > 解决方案 > 我想检查是否满足 4 个条件应该发生什么

问题描述

我还是 c# 的新手,我正在尝试编写一个代码来检查我的 if 条件,如果满足 4 个条件,那么就会发生一些事情。这是我的代码:enter code here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;
public class NameTrans : MonoBehaviour {
    public string thename;
    public GameObject inputField;
    public GameObject textDisplay;
    public GameObject textDisplay2;

    // Use this for initialization
    public void Showname () {
        thename = inputField.GetComponent<Text>().text;
     if (thename.ToUpper().Contains("Man".ToUpper()) || thename.ToUpper().Contains("Dog".ToUpper()))
        {

            textDisplay2.SetActive(false);
            textDisplay.SetActive(true);
            textDisplay.GetComponent<Text>().text = "WOrks" ;
        }
       else
        {
            textDisplay.SetActive(false);
            textDisplay2.SetActive(true);
            textDisplay2.GetComponent<Text>().text = "Not WORK" ;
        }

            }


}


标签: stringunity3dif-statement

解决方案


如果只需要满足 4 个条件中的一个,那么您已经在做正确的事情了。您只需要添加缺少的两个条件。

if((thename.ToUpper().Contains("Man".ToUpper())) || 
   (thename.ToUpper().Contains("Dog".ToUpper())) ||
   (thename.ToUpper().Contains("Cat".ToUpper())) ||       
   (thename.ToUpper().Contains("Fish".ToUpper())))
{
    //do something
}
else
{
    //do something else
}

如果需要满足所有 4 个条件,则需要用“&&”而不是“||”连接条件。

if((thename.ToUpper().Contains("Man".ToUpper())) && 
   (thename.ToUpper().Contains("Dog".ToUpper())) &&
   (thename.ToUpper().Contains("Cat".ToUpper())) &&       
   (thename.ToUpper().Contains("Fish".ToUpper())))
{
    //do something
}
else
{
    //do something else
}

更新新信息 如果您想检查 x 条件中的任何 4 个是否为真,我可能会执行以下操作:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;
public class NameTrans : MonoBehaviour {
    public string thename;
    public GameObject inputField;
    public GameObject textDisplay;
    public GameObject textDisplay2;
    private string[] conditions;
    private int counter;

    // Use this for initialization
    public void Showname () {
     thename = inputField.GetComponent<Text>().text;
     conditions = {"Man", "Dog", "Cat", "Fish", "Goat", 
                   "Frog", "Bird", "Alligator"};
     counter = 0;

     foreach(string cond in conditions)
     {
         if (thename.ToUpper().Contains(cond.ToUpper())
         {
             counter += 1;
             if (counter >= 4)
             {
                 break;   
             }
         }
     }

     if (counter >= 4)
        {

            textDisplay2.SetActive(false);
            textDisplay.SetActive(true);
            textDisplay.GetComponent<Text>().text = "WOrks" ;
        }
       else
        {
            textDisplay.SetActive(false);
            textDisplay2.SetActive(true);
            textDisplay2.GetComponent<Text>().text = "Not WORK" ;
        }

    }


}

推荐阅读