I know similar questions have been answered before but their solutions don’t seem to help me. Here is the part of my script that has an issue:

tugle = GameObject.FindGameObjectWithTag(“musicToggle”).GetComponent();

“tugle” is defined up top as a public Toggle, and I’m using UnityEngine.UI. However it says the object is not referenced. I’ve also tried doing

tugle = GameObject.FindGameObjectWithTag(“musicToggle”);

In which case it just tells me that it cannot convert GameObject to Toggle. Any suggestions?

Hi,

tugle = GameObject.FindGameObjectWithTag("musicToggle") 

In this it is giving error" it cannot convert GameObject to Toggle" because you have taken tugle to be toggle object and assigning it a gameObject which is wrong.
You should probably do -

  1. Assign tugle from inspector.
    or

    tugle = GameObject.FindGameObjectWithTag(“musicToggle”).GetComponent();`

hope it works for u.

GameObject gameobject = GameObject.FindGameObjectWithTag (“musicToggle”);

tugle = gameobject.Toggle;

Basically what is done is a GameObject is defined in the script and the first GameObject with the tag musicToggle,

then, assuming tugle is defined as Toggle tugle = new Toggle();

then the next statement will set tugle as that GameObject’s Toggle.


Here is an explanation of your code:

tugle = GameObject.FindGameObjectWithTag("musicToggle").GetComponent();

What ends up happening is you are defining a Toggle(tugle) as a GameObjects’ Component’s type, but nothing more.

In your second attempt you run into the issue where You are attempting to define a Toggle as a GameObject, which is impossible.