Home > Net >  C#/Unity2D | Can't access public class method
C#/Unity2D | Can't access public class method

Time:04-12

I am currently learning Unity and have a question regarding C#. I have defined a class like this:

using UnityEngine;

public class ObscuringItemFader : MonoBehaviour
{
     private SpriteRenderer spriteRenderer;

     private void Awake()
     {
          spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
     }

     public void FadeOut()
     {
          StartCoroutine(FadeOutRoutine());
     }

     public void FadeIn()
     {
          StartCoroutine(FadeInRoutine());
     }

Creating a instance of it works flawlessly, however when I call a public method like I do here:

using UnityEngine;

public class TriggerObscuringItemFader : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other) 
    {
        ObscuringItemFader[] obscuringItemFader = other.gameObject.GetComponentsInChildren<ObscuringItemFader>();
        if(obscuringItemFader.Length > 0)
        {
            for(int i = 0; i < obscuringItemFader.Length; i  )
            {
                obscuringItemFader[i].FadeOut();
            }
        }
    }

It throws me an error stating: "ObscuringItemFader" does not contain a definition for FadeOut.

Does anyone know what exactly is wrong here? Hopefully not just a silly syntax error that I am unable to locate.

Thank you so much in advance!

CodePudding user response:

I cannot find any error with the logic or syntax of this code (other than technically missing class end brackets).

There is potentially another error in a different script that is causing one of these scripts to be unable to compile correctly.

You can select Build > Build Solution in visual studio and if there are any other compile errors causing changes to these scripts to not be applied.

CodePudding user response:

I solved it! Thanks to @Kalib Crone who assured me that there are no logic/syntax errors I decided to move from VS Code to VS 2022 and look at that, for some reason the ObscuringItemFader class was empty when I opened it with Visual Studio!

When I reopened it in VS Code, the code shown above was there again, but neither Unity nor VS 2022 seem to see it when I open the file with them.

  • Related