Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Question GetComponent returns error although the component referenced exists

Discussion in 'Scripting' started by HowStressful, Jan 9, 2023.

  1. HowStressful


    Aug 20, 2022
    This code
    Code (CSharp):
    1. GameObject.Find("Background").GetComponent<Image>().sprite = Resources.Load<Sprite>("images/bggamestall");
    returns the following error:
    Code (CSharp):
    1. ArgumentException: GetComponent requires that the requested component 'Image' derives from MonoBehaviour or Component or is an interface.
    2. UnityEngine.GameObject.GetComponent[T] () (at <bdd20210bb844b2e88e1149ea99da5ef>:0)
    3. TEST.Start () (at Assets/scripts/TEST.cs:16)
    However, the object Background referenced is a UI image object, so Image is a component under it. The required modules and libraries have already been included.
  2. spiney199


    Feb 11, 2021
    You're reading the error wrong. It's complaining that Image isn't a type that inherits from Component, though UnityEngine.UI.Image does inherit from Component, so I'm not sure why this error is occuring.

    You don't have your own
    class somewhere?
    Bunny83 likes this.
  3. angrypenguin


    Dec 29, 2011
    There are multiple classes called "Image" in various different libraries. Either you've got an Image class in your code, or you've got a "using" statement at the top of the file for another namespace which does, and the compiler is looking at the wrong Image class as a result.

    So, first, check your "using" statements to make sure there's no unnecessary junk being included by accident. Modern code editors often try to be helpful by including namespaces they think you need, but they can be a little trigger happy.

    Sometimes you need to have multiple namespaces where classes have the same name. In those cases you can specify which class you want by writing the fully qualified name, as spiney did above, i.e. "UnityEngine.UI.Image" instead of just "Image".
  4. runner78


    Mar 14, 2015
    Could it be using the UI Toolkit Image?
    Bunny83 and spiney199 like this.