Home > Net >  Failure to find correct component with GetComponent function in Unity
Failure to find correct component with GetComponent function in Unity

Time:11-28

I'm going to use the BrowserButton to open the BrowserWindow, a internal browser in the Unity app. Which is redirect with the link string contained in the BrowserButton's onClick function.

However, when I wrote the script for opening the BrowserWindow, it was not able to find the component running the browser. enter image description here

Here is my hierarchy below. BrowserWindow is the component contains browser and control buttons. webView is the component to rendering browser itself. BrowserButton is the button to call the window out, and provide the link string to redirect - like a bookmark on desktop.

enter image description here

And my script is down below.

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

public class OpenCloseOption : MonoBehaviour
{
    // Close the browser window with the cross button
    public void Close()
    {
        gameObject.SetActive(false);
    }

    // Open the browser with preset link
    public void Open()
    {
        gameObject.SetActive(true);
    }

    // Open the browser window with bookmark button
    public void OpenLikns(string link)
    {
        gameObject.SetActive(true);
        Canvas.GetComponent<BrowserWindow.webView>.Navigate(link);
    }
}

Anyone can help me to figure out which component name or hierarchy is not correct?

CodePudding user response:

BrowserWindow and webView are not components. They are GameObjects. To get a reference to them, use the following:

[SerializeField] private GameObject browserWindow;
[SerializeField] private GameObject webView;

Then click on the game object with the OpenCloseOption component. There will be two slots for the browser window and web view. You can drag the game objects into the slots to create the references.

I'm not sure where the Navigate() method comes from, but you can't call it on a game object. If you have a MonoBehavior attached to webView with a public method Navigate, you could do something like webView.GetComponent<ScriptWithNavigateMethod>().Navigate().

  • Related