GUI functions inside OnGUI giving argument exception

I’m using the following code:

using UnityEngine;
using System.Collections;

public class TestScript{
 
 private GUISkin custom_skin;
 public bool guiEnabled;
 
 public TestScript(GUISkin new_skin){
 custom_skin = new_skin;
 }
 
 public void OnGUI(){
 if(guiEnabled){
 GUI.skin = custom_skin;
 GUI.Label(new Rect(0,0,50,50),"Blah");
 }
 }
}

The problem is that I’m also getting the following error: ArgumentException: You can only call GUI functions from inside OnGUI.

It works fine in another script that is running in the same scene, but for some reason this one won’t. I looked at the other script, and it’s all set up in exactly the same way, but for some reason I’m getting this error all of a sudden.

Your TestScript doesn’t inherit from MonoBehaviour so I presume you are calling its OnGUI yourself somewhere - it needs to be called from within a real OnGUI for it to work.

I am trying to use a similar thing, but the OnGUI() in the class wont work for the class objects. I want to call a render function in another script that then renders the class object, but the script never runs the OnGUI() function of that class object. What do?