I got an error but I'm not sure how to fix it

I got this error “ArgumentException: GetComponent requires that the requested component ‘GameObject’ derives from MonoBehaviour or Component or is an interface.” I looked a little bit online, and I think I understand what went wrong, but I’m not entirely sure how to fix it. Here is the line of code that is causing the error: PathNode = GetComponentInChildren<GameObject[]>(); (Sorry if this isn’t how your supposed to show your code, I think I did it right but idk) I know that I’m supposed to change the GameObject to a component, the thing I can’t quite wrap my head around is that I don’t have any components assigned to the game objects in the list. The project is also 2D in case that’s important info. Thank you in advance for anyone’s help. If the solution is something as simple as adding a rigidbody or something, then sorry for the yap session over nothing.

You can fix your own typing mistakes. Here’s how:

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

Since an array of GameObject could never be a Component (generally nothing is interchangeable), perhaps you should start with this checklist:

How to report your problem productively in the Unity3D forums:

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

If you post code, only post the relevant code and always use the format button above. Do not post photographs of code.

Remember, we are not here to do your work! You are going to do your work yourself, perhaps based on our answers to your questions. Therefore it is of critical importantance that you ask the question well if you want useful answers.

You pass an array to GetComponentInChildren that requires ComponentType, so you need to pass the correct entity — literally the type of components you want to find, e.g.:

HingeJoint hinge = GetComponentInChildren<HingeJoint>();

Just in case PathNode is defined as:

GameObject[] PathNode;

And you intended to get an array of GameObjects rather than components, then you can’t use GetComponent*().

Since the engine doesn’t know which game objects you want, you need to be specific.

Ideally assign the nodes by dragging them in the PathNode list in Inspector when the field is public or [SerializeField]:
public GameObject[] PathNode;

Otherwise if the path nodes are children of the script object you could add all of them to an array:

    var childCount = transform.childCount;
    PathNode = new GameObject[childCount];

    for (int i = 0; i < childCount; i++)
        PathNode[i] = transform.GetChild(i).gameObject;

However this would be redundant since you can always enumerate (foreach) the transform which will go over each child:

foreach (Transform child in transform)
    Debug.Log(child.name);

Other ways include tagging each path object with a component, and then using PathNode = Object.FindObjectsByType<T>(..);

FYI: I removed the Tilemap tag and added the Scripting tag for you so your post is now in the correct forum area.

Please try to add tags that directly relate to your question so your post is placed in the most suited area.

Thanks!

It’s not clear from the question what you’re trying to do. What are the PathNodes? GameObjects that you’re trying to get from your scene, or components attached to the GameObject with this script? Something else?

Take this opportunity to repost your code and your question. Imagine for a moment that someone you know told you “I’m getting an error on my computer”. What could you possibly do with so little information?

It isn’t the specific line of code that matters. Typically you should post the entire class (formatted as code BTW) and then quote the error verbatim. If it mentions a line number we would/should be able to see that line but also the definitions and declarations involved.

The problem often isn’t a line, the problem is the situation. We need to see the situation.

Here is the entire script:

using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;

public class PlayerController : MonoBehaviour
{

    public GameObject[] PathNode;
    public GameObject Player;
    public float MoveSpeed;
    float Timer;
    static Vector3 CurrentPositionHolder;
    int CurrentNode;
    private Vector2 StartPosition;

    public UIDocument gameUILayout;
    private Button rollButton;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        PathNode = GetComponentInChildren<GameObject[]>();
        CheckNode();

        rollButton = gameUILayout.rootVisualElement.Q<Button>("RollDice");
        rollButton.clicked += OnRollButtonClick;
    }

    // Update is called once per frame
    void Update()
    {
        Timer += Time.deltaTime * MoveSpeed;

        if (Player.transform.position != CurrentPositionHolder)
        {

            Player.transform.position = Vector3.Lerp(StartPosition, CurrentPositionHolder, Timer);
        }

    }

    void OnRollButtonClick()
    {
        var diceRoll = Random.Range(1, 7);
        Debug.Log("You rolled a: " + diceRoll);
    }

    void CheckNode()
    {
        Timer = 0;
        StartPosition = Player.transform.position;
        CurrentPositionHolder = PathNode[CurrentNode].transform.position;
    }
}

The path nodes are a series of sprites I have that are not children of the script game object. This is the exact error message "ArgumentException: GetComponent requires that the requested component ‘GameObject’ derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponentInChildren (System.Type type, System.Boolean includeInactive) (at :0)
UnityEngine.Component.GetComponentInChildren (System.Type t, System.Boolean includeInactive) (at :0)
UnityEngine.Component.GetComponentInChildren[T] () (at :0)
PlayerController.Start () (at Assets/Scripts/PlayerController.cs:25)
" It was long, so I didn’t include all of it. I apologize for being vague and doing this whole discussion thing wrong, I just needed clarity on what I did wrong and how to fix it. Coding isn’t my passion or anything I’m just in a coding class and I need a good grade, so I have trouble understanding a lot of words and phrases in code. If I’m still doing something wrong let me know.

That helps a lot. It is also helpful (for you not us) to explain what your purpose is, i.e. what you want an array of GameObjects named PathNode for. There are often good alternatives if we understand the end goal.

I will assume that type you passed into GetComponentInChildren isn’t legitimate as a type. And it may be that you meant to use GetComponentsInChildren if you are looking for multiple components.

Since this is public, you can simply assign the GameObjects in the Inspector by dragging them onto the field/list labelled Path Node.

Btw, if you change the type to Transform[] that would be even more convenient since you will likely only use the object’s Transform properties, and thus the code would be a bit shorter:

CurrentPositionHolder = PathNode[CurrentNode].position;

If you want to “find” the path nodes somehow, you have to do so in a manner where you actually get the desired objects.

Find() (by name) is generally to be avoided since it’s slow and unreliable because you can make a typo both in the object’s name and in the query. It also doesn’t allow something like “find all objects whose name contains X” - that would require manually going over all objects in the scene.

The alternative is to add a “tag” component to each path node and use Object.

PathNode = FindObjectsByType<PathNodeTag>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);

Where the PathNodeTag component is just a MonoBehaviour with no code inside.