-2

Im facing problem in accessing SerializeField inside the method that is implemented from a interface.

public class UIManager : MonoBehaviour, IGameOver
{
[SerializeField] 
public GameObject gamePlayPanel;
[SerializeField]
public GameObject gameOverPanel;

[Header("Score-board")]
public Text coinScoreText;
public Text diamondScoreText;

private static int coinScore, diamondScore;

public void EndGame(string reason)
{

    Debug.LogError(gamePlayPanel);  // returning NULL
    Debug.Log("Game Over: UI Manager " + reason);

    gamePlayPanel.SetActive(false); 
    gameOverPanel.SetActive(true);


}
}

And the interface looks like below

public interface IGameOver
{
    void EndGame(string reason);
}

Is there any other way of accessing SerializeField inside the EndGame() method which is overrided from IGameOver interface

Kushal P
  • 7
  • 2
  • You may just check for null: `if (gamePlayPanel != null)` – Klaus Gütter Sep 06 '21 at 13:58
  • Yes, but I need to access gamePlayPanel field, and it is working outside the EndGame(). – Kushal P Sep 06 '21 at 14:04
  • Interface has nothing to do with the GameObject panels. – Serge Sep 06 '21 at 14:30
  • 1
    @KlausGütter while this prevents the exception itself it just obfuscates the actual issue making debugging a lot harder. The exception at least immediately tells you what is wrong instead of simply nothing happening at all ;) – derHugo Sep 06 '21 at 16:27

1 Answers1

0

Regardless of the implementation of the interface, the object itself and its children can always access public/protected functions and variables at any time.

So, in the code above, accessing the SerializeField instance inside the EndGame() function scope shouldn't be a problem.

Check out the two lists below.

First, make sure you have connected the Monobehaviour to the SerializeField in the Unity Editor's Inspector window.

Second, make sure that the gamePlayPanel and gameOverPanel objects are destroyed by the OnDestroy function at the moment the EndGame function is executed. This is a matter of order, so you need to think carefully about the order of execution of your code.

ggzerosum
  • 56
  • 4