1

I have 2 classes for this operation:

  • SetFaces
  • ChangeImage

  • ChangeImage passes the appropriate index it has to SetFaces, so it prints the specific images it needs.

  • SetFaces contains a method with a switch case to insert the right images into the component.


Into the class ChangeImage, the calling method to SetFaces is:

SetFaces.SetButtonsImages(index);

The class SetFaces is this:

public class SetFaces : MonoBehaviour
{
    public Button btnA, btnB, btnC, btnD;
    public Sprite
        Img0_A, Img0_B, Img0_C, Img0_D,
        Img1_A, Img1_B, Img1_C, Img1_D,
        /* ... */
        Img7_A, Img7_B, Img7_C, Img7_D,
        Img8_A, Img8_B, Img8_C, Img8_D;

    public static void SetButtonsImages(int index)
    {
        switch (index)
        {
            case 0:
                btnA.GetComponent<Image>().sprite = Img0_A;
                btnB.GetComponent<Image>().sprite = Img0_B;
                btnC.GetComponent<Image>().sprite = Img0_C;
                btnD.GetComponent<Image>().sprite = Img0_D;
                DebugDisplay.PrintText("Set Faces 0");
                break;

            case 1:
                btnA.GetComponent<Image>().sprite = Img1_A;
                btnB.GetComponent<Image>().sprite = Img1_B;
                btnC.GetComponent<Image>().sprite = Img1_C;
                btnD.GetComponent<Image>().sprite = Img1_D;
                DebugDisplay.PrintText("Set Faces 1");
                break;

            /* ... */

            case 8:
                btnA.GetComponent<Image>().sprite = Img8_A;
                btnB.GetComponent<Image>().sprite = Img8_B;
                btnC.GetComponent<Image>().sprite = Img8_C;
                btnD.GetComponent<Image>().sprite = Img8_D;
                DebugDisplay.PrintText("Set Faces 8");
                break;
        }
    }
}
  • Does this answer your question? [CS0120: An object reference is required for the nonstatic field, method, or property 'foo'](https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop) – Yong Shun Aug 04 '22 at 10:20

1 Answers1

1

The error quite explains it. You are calling a non-static item on a static method. there are 3 ways to solve this

Option 1

Remove the static from the buttons method so it reads

public void SetButtonsImages(int index)

Option 2

initialize the SetFaces class

so you will have

var btn = new SetFaces ();

and then use btn to access them.

Option 3

Make everything static

    public static Button btnA, btnB, btnC, btnD;
    public static Sprite
        Img0_A, Img0_B, Img0_C, Img0_D,
        Img1_A, Img1_B, Img1_C, Img1_D,
        /* ... */
        Img7_A, Img7_B, Img7_C, Img7_D,
        Img8_A, Img8_B, Img8_C, Img8_D;

Let me know how this works for you in case I need to improve on the answer.

For further Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0120

mw509
  • 1,957
  • 1
  • 19
  • 25