Unity 3d & C#, if gameObject != this

问题描述 投票:1回答:1

我有这段代码,我在 "if (planet != this)... "上有问题。

public class Gravity : MonoBehaviour
{
    GameObject[] planets;

    // Start is called before the first frame update
    void Start()
    {
        planets = GameObject.FindGameObjectsWithTag("Planet");
    }

    // Update is called once per frame
    void Update()
    {
        foreach (GameObject planet in planets)
        {
            if (planet != this)
            {
                //do things
            } 
        }
    }
}

我在 "if (planet != this)... "上遇到了一个问题 我希望出现的情况是 如果planets[index] == gameObject 那么 "planet != this "将返回false. 但这是行不通的,我该如何解决呢?

c# unity3d if-statement this
1个回答
2
投票

this 是一个关键字,它指的是当前对象的实例,在本例中是一个 Gravity 类,所以每 GameObject 对象不同于 Gravity 的例子。你可以做这样的事情,以访问所附的 GameObject:

foreach (GameObject planet in planets)
{
   if (planet != this.gameObject)
   {
      // Do magic stuff...
   } 
}
© www.soinside.com 2019 - 2024. All rights reserved.