Home > OS >  Why using getComponent to call objects in Unity?
Why using getComponent to call objects in Unity?

Time:01-07

I am new in unity, I'm just wondering why we call the player object like this :

    private void OnTriggerEnter(Collider other)
    {
        // if the player hit the enemy then destroy the ememy
        if (other.tag == "PLAYER" ) {
            // like this
            other.transform.GetComponent<Player>().damage();  
        }

while we can make the damege method static and call it like this :

    private void OnTriggerEnter(Collider other)
    {
        // if the player hit the enemy then destroy the ememy
        if (other.tag == "PLAYER" ) {
            //other.transform.GetComponent<Player>().damage();
            Player.damage(); 
        }

why we call the object like this what the point

other.transform.GetComponent<Player>().damage();

does it effect performance ? or is it just another available way to call objects

CodePudding user response:

I will try to explain this the best I can. This explanation isn't perfect, but I worded it so it makes the most sense. A class is a file that contains code. There are two "types" of classes, static and non-static. Static classes can be accessed anywhere, but there is only ever 1 copy. For example, use UnityEngine.Mathf. That is a static class, so you can just do Mathf.(whatever).

The non-static class can have multiple copies. Non-static classes can have static methods and fields, which can be accessed like you would a static class. For most basic applications, these classes just use normal methods. These methods are instance-dependent.

For example, take a non-static Player class.

public class Player : MonoBehaviour {
    //This is accessed using Player.instance
    public static Player instance;
    //This function only runs on the script you place on a GameObject
    public void Start(){
        //Sets the static instance to this instance
        instance = this;
    }
}

You can then access the active player instance with any other script (as long as the instance variable was set before)

public Player GetPlayer() {
    //As you can see, you don't need a reference to a Player; you can just use the static instance.
    Player instance = Player.instance;
    return instance;
}

In conclusion, using Player.Whatever references the static version. Using playerInstance.Whatever references a runtime instance. If you will only have one runtime instance of a class, you can use the example above to allow other classes to access the instance.

  • Related