I found a nice way to use tags and scenes

I found a nice way to use tags and scenes.

public static class Tags
{
    public readonly static string Player = "Player";
    public readonly static string Fire = "Fire";
}
public static class Scenes
{
    public readonly static string Main = "Main";
}

Create classes for tags and scenes as shown above.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag(Tags.Fire))
        {
            Debug.Log("Player collided with Fire.");
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class RetryButton : MonoBehaviour
{
    public void ReTry()
    {
        SceneManager.LoadScene(Scenes.Main);
    }
}

Use tags and scenes as above.





How about using tags and scenes with the code above?
It is expected to solve problems caused by string typos.

Is there anything that could be a problem?

2 Likes

I don’t see any problems, but I do have a suggestion;
Use const instead of readonly static for these. It is generally accepted that you should use const when the values can be defined at compile time, as is the case here. Use readonly static (or static readonly) when the value can only be determined at runtime, but it will not change. For example

public const string NOTHING = ""; // defined at compile time
public static readonly string ALSO_NOTHING = string.Empty; // this can only be determined at runtime

It’s just a suggestion and you can use what you have without problems, it’s just what’s generally accepted

‘readonly’ is used to emphasize that it is read-only.
Am I using ‘readonly’ wrong?

I tried using ‘readonly’ and ‘const’ together.
A compilation error appears.

I think I should use it as you wrote.
It seems that only one of ‘const’ and ‘readonly static’ can be used.

Please recommend a folder name to contain ‘Tags.cs’ and ‘Scenes.cs’.
I am currently using the folder name ‘Metadata’.
However, ‘Tags.cs’ and ‘Scenes.cs’ are not metadata.

Yeah, const is already readonly. const fields cannot be changed at runtime, but static fields can. Adding readonly to the static fields make it so they can’t change at runtime.

Like I said; you don’t have to change it, it’s fine as it is.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms