Is it more efficient to use events when changing another class variable than directly accessing the variable? How about security? What about the properties?

I simplify the situation as much as I can:

class 1:

public class GameFlowManager { 
    public float worldSpeed;
}

class 2:

public class Clouds {
    void MoveClouds(float worldSpeed){...}

I need to access worldSpeedfrom Clouds.
Which method is more effective?

  • Using GameFlowManager gfm = FindObjectOfType<GameFlowManager>() then accessing the variable with a pointer (I know this is not a pointer, but the goal is the same)

    gfm.worldSpeed
  • Or should I use an event that calls the setter function on the classes that need it worldSpeed? That way I would not need the public variable.

Now it is only for unity, when I cannot use properties. In simple C # code, I can use getters without any consequences, right?

+4
1

, "" ( , , ), Singleton, :

class GameFlowManager
{
    public static GameFlowManager Instance {get; private set;}

    public float worldSpeed{get; set;} // You could make the setter private to prevent other classes from modifying it if necessary

    void Awake()
    {
        Instance = this; // Note that this requires an object of type GameFlowManager to already exist in your scene. You could also handle the spawning of this object automatically to remove this requirement.
    }

    ...
}

, , :

GameFlowManager.Instance.worldSpeed

.


: , ?

+2

Source: https://habr.com/ru/post/1671507/


All Articles