What is the best practice of using a static variable in C # Unity

Accordingly, the tutorial demonstrated on youtube

He is trying to make a static variable to hold the score and change it in other scenarios when the player should be awarded, but he also said that using a static variable in C # script Unity is not recommended.

The flow is what I do to build a scoring system:

in ScoreManger, which was associated with the UI component of the text-based interface, to show appreciation:

public class ScoreManager : MonoBehaviour {
    public static int score;
    Text text;
    private void Awake()
    {
        text = GetComponent<Text>();
    }
    private void FixedUpdate()
    {
        text.text = "Score: " + score;
    }
}

And the procedure for adding ratings:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        ScoreManager.score = ScoreManager.score + score;
        Destroy(gameObject);
    }
}

So, what is the best way to do this without a static variable, and if someone can explain why using a static variable is not recommended, be more grateful.

EDIT

, @rogalski , IDE , - ExecuteEvents.Execute<T> enter image description here

+4
2

, Unity - , , . , , , ( ) - .

Unity ( ), , ..

, .

(EDIT → EventData, Unity)

:

public interface ICoinPickedHandler: IEventSystemHandler
{
    void OnCoinPickedUp(CoinPickedEventData eventData);
}

EventTarget script:

public class ScoreManager
    : MonoBehaviour, ICoinPickedHandler
{
    private int m_Score;

    public void OnCoinPickedUp(CoinPickedEventData eventData)
    {
        this.m_Score += eventData.Score;
        eventData.Use();
    }

    // code to display score or whatever ...
}

:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        // assuming your collision.gameObject
        // has the ICoinPicker interface implemented
        ExecuteEvents.Execute<ICoinPickedHandler>(collision.gameObject, new CoinPickedEventData(score), (a,b)=>a.OnCoinPickedUp(b));
    }
}

EventData:

public class CoinPickedEventData
    : BaseEventData
{
    public readonly int Score;

    public CoinPickedEventData(int score)
        : base(EventSystem.current)
    {
        Score = score;
    }
}

, , . , ExecuteHierarchy.

docs.unity3d.com.

+4

, : addToScore, .

: , singleton . , , , reset , .

+1

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


All Articles