C # - не удалось вызвать другой скрипт - PullRequest
0 голосов
/ 20 февраля 2019

Я создал два сценария.Один включает переменную и метод.Задача второго скрипта - вызвать первый скрипт и получить доступ к его компоненту.Однако я получаю следующую ошибку:

ThisScriptWillCallAnotherScript.Update () (at Assets / Scripts / ThisScriptWillCallAnotherScript.cs: 21)

Я попытался удалить строку, на которую ссылается, но ошибка сохраняется,Есть идеи, что я могу делать не так?

Сценарий 1:

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

public class ThisScriptWillBeCalledInAnotherScript : MonoBehaviour {

    public string accessMe = "this variable has been accessed from another script";

    public void AccessThisMethod () {
        Debug.Log ("This method has been accessed from another script.");
    }
}

Сценарий 2:

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

public class ThisScriptWillCallAnotherScript : MonoBehaviour {

    // below we are calling a script and giving a name//
    ThisScriptWillBeCalledInAnotherScript callingAScript;

    void Start () {
        //here we are using GetComponent to access the script//
        callingAScript = GetComponent<ThisScriptWillBeCalledInAnotherScript> ();
        Debug.Log ("Please press enter key...");
    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown (KeyCode.Return)) {
            Debug.Log ("this is the script we just called " + callingAScript);
            Debug.Log (callingAScript.accessMe); // we are accessing a variable of the script we called
            callingAScript.AccessThisMethod (); // we are calling a method of the script we called
        }
    }
}

1 Ответ

0 голосов
/ 20 февраля 2019

Это Unity GameObjects может иметь Компоненты.Метод GetComponent<T>() получает ссылку на компонент T из текущего GameObject.

Так что если ваш GameObject имеет оба компонента (ScriptA и ScriptB)

enter image description here

, тогда будет возвращена "ненулевая" ссылка на экземпляр ScriptB:

public class ScriptA : MonoBehaviour {

    ScriptB scriptB;

    // Use this for initialization
    void Start () {
        scriptB = GetComponent<ScriptB>(); //Not null if GameObject has ScriptB component.
    }
}

Если в вашем GameObject нет компонента ScriptB, тогда метод GetComponent<T>() вернет ноль.

Если ScriptB является компонентом другого GameObject, вам понадобится ссылка на этот другой GameObject и вызовите его через OtherGamoeObject.GetComponent<T>() Если ScriptB даже не является Scriptэто изменило GameObject и просто (например) содержит некоторые математические вычисления или около того, тогда я бы предложил не делать его наследуемым от Monobehaviour, а просто создать экземпляр следующим образом: var scriptB = new ScriptB();

...