I create an array called Zombies
which includes all the Game Object in the scene. And I also create the foreach loop to check if the Zombies
have attached ZombieState.cs
. I'm following the book but it's not explaining clearly why we need zState==this
.
using UnityEngine;
public class ZombieState : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GameObject[] Zombies = (GameObject[])GameObject.FindObjectsOfType(typeof(GameObject));
foreach (GameObject go in Zombies)
{
ZombieState zState = go.GetComponent<ZombieState>();
if (zState == null || zState == this)
{
continue;
}
}
}
}
CodePudding user response:
In general, the this
keyword refers to the current instance of a class and is often used to distinguish between instance variables and local variables with the same name. In your case, this
refers to the ZombieState
component attached to the current GameObject
, while zState
refers to the ZombieState
component being iterated over in the for-each
loop.
zState == this
is a comparison that checks if the ZombieState
component of the current GameObject
(referenced by the this
keyword) is the same as the ZombieState
component that is being iterated over in the for-each
loop. That was obtained via GameObject[])GameObject.FindObjectsOfType(typeof(GameObject))
.
If zState == this
is true
, it means that the current ZombieState
component being iterated over is the same as the ZombieState
component of the current GameObject
. In this case, the code will skip over the current iteration of the for-each
loop and move on to the next one.
CodePudding user response:
this
is a C# statement that simply refers to “this” class.
In your example, if you read through the code, you’re asking Unity to list all of the instances of ZombieState
. The class you’re calling this from IS also a ZombieState
. So in essence the code is asking for ALL the instances of ZombieState
, and when it comes time to do something with all of the instances, the foreach
statement, we want to do it to all the other instances.