You can only call GUI from inside OnGui

Hello Guys!

I’m completly new to the world of Unity. I wannna programm a litte strategygame. But i got this Error in Unity with my script: ArgumentException: You can only call GUI functions from inside OnGUI.

I also get the Error Object reference not set to an instance of an object.
ROW 24 in the code.

I added the code below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BuildingManager : MonoBehaviour {

    [SerializeField]
    private GameObject placeableObject1;

    private GameObject currentObject;
 
    // Use this for initialization
    void Start () {
    }
 
    // Update is called once per frame
    void Update () {

        OnGUI();
    
    }
    private void MoveCurrentObject()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit hitInfo;
        if(Physics.Raycast(ray, out hitInfo))
        {
            currentObject.transform.position = hitInfo.point;
        }
    }
    void OnGUI()
    {
            if(GUI.Button(new Rect(Screen.width/20,Screen.height/15 + Screen.height/12 ,100,30), text: "Barrake"))
            {
                if(currentObject == null)
                {
                    currentObject = Instantiate(placeableObject1);
                }
                else
                {
                    Destroy(currentObject);
                }
            }

        if (currentObject != null)
        {

            MoveCurrentObject();
        }

    }

}

Greatings Max

@Maxi_Hraschan

Hi - Not many are going to click, download and open some attachment, just put your code here in your post as code block. See this sub-forum’s pinned post for how to use code tags:

Oh sry, didn’t know. Changed my post.

Hi,

AFAIK you don’t have call OnGUI method in your update, it gets called automatically by Unity.

1 Like

Ohh yes thanks man :slight_smile: Can somebody close my Post ?