简体   繁体   中英

C# Make a class return its instance without a function or variable

So I've been working with classes with single instances in Unity for a while and generally do this:

class PublicThings {
    public static PublicThings I; // instance of this class
    public int Score;
    void Start { I = GetComponent<PublicThings>(); }
}

Usage: PublicThings.I.Score = 10;

Which works pretty well. However, I've been curious as to whether or not it's possible to have the instance of the class be returned without having to type .I after the class.

So basically here's how it would look instead:

PublicThings.Score = 10;

This question seems like it's relevent but I'm having trouble getting it to work.

Is this possible? If so, how would it be done?

Three options to do what you are looking to do:

  1. Make a static property/field with the static keyword in the PublicThings class
  2. Make a ScriptableObject and attach it to the item that is calling it ( video tutorial )
  3. Utilize the Singleton Pattern (I would suggest avoid using this method before trying the other two)

Also it's worth noting that the Singleton Pattern doesn't necessarily solve your problem. You will still have to call something like PublicThings.instance.Score .

Hope this helps.

Singleton pattern is the way to go.
Also, with lazy instantiation.

public class PublicThings
{
    private static PublicThings _instance;

    // Your private constructor
    private PublicThings() { }

    public static PublicThings Instance
    {
        get
        {
            if (_instance == null)
            {
                // Construction of instance logic here
                _instance = new PublicThings();
            }

            return _instance;
        }
        // No setter, read-only property
    }

    // Decide if Score is a read-only property or not.
    public int Score { get; set; }
}

Whener the single instance of PublicThings is required, it will be constructed and then stored. A second access to the instance will provide the stored one.

[Test]
public void WithTwoAccess_ToSingleInstance_MustBeTheSame()
{
    var things1 = PublicThings.Instance;
    var things2 = PublicThings.Instance;

    Assert.AreSame(things2, things1);
    // Asserts true
}

If your Score property must be set once, just change que Instance property to a method (commonly called GetInstance ) which expects the value of Score .

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM